型アサーション
TypeScript でコンパイラに型情報を明示的に伝える構文で、誤用するとランタイムエラーの原因になる
TypeScript型安全
型アサーションとは
型アサーション (Type Assertion) は、TypeScript のコンパイラに「この値はこの型である」と明示的に伝える構文である。as キーワードで記述する。コンパイラの型推論を上書きするため、誤用するとランタイムエラーの原因になる。型キャスト (Type Cast) とは異なり、実行時には何も起きない。
基本的な使い方
// コンパイラが型を推論できない場合に使う
const element = document.getElementById('app') as HTMLDivElement;
// JSON.parse の戻り値は unknown
const data = JSON.parse(body) as User;
// イベントハンドラー
const target = event.target as HTMLInputElement;
console.log(target.value);
型アサーションの危険性
// ❌ 危険: 実際の値と型が一致しない
const user = { name: 'Alice' } as User; // User に email が必須でも通る
console.log(user.email.toLowerCase()); // ランタイムエラー!
// ❌ 危険: API レスポンスを検証なしでアサーション
const response = await fetch('/api/users/123');
const user = await response.json() as User; // レスポンスが User 型とは限らない
型アサーションはコンパイラの型チェックをバイパスする。実際の値が型と一致しなくても、コンパイルエラーにならない。
型アサーションの代替手法
型ガード (推奨)
// ✅ 型ガード: 実行時に型を検証
function isUser(value: unknown): value is User {
return typeof value === 'object' && value !== null
&& 'name' in value && 'email' in value;
}
const data: unknown = JSON.parse(body);
if (isUser(data)) {
console.log(data.email); // 安全: 型が検証済み
}
Zod によるバリデーション (推奨)
import { z } from 'zod';
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
});
// ✅ バリデーション + 型推論
const user = UserSchema.parse(JSON.parse(body));
// user は { name: string; email: string } 型に推論される
// バリデーション失敗時は ZodError がスロー
型アサーションが許容されるケース
| ケース | 理由 |
|---|---|
| DOM 要素の取得 | getElementById の戻り値は HTMLElement | null |
| テストコード | モックオブジェクトの型を合わせる |
| 外部ライブラリの型定義が不正確 | 型定義のバグを回避 |
Non-null Assertion (!)
// ❌ Non-null Assertion: null チェックをスキップ
const element = document.getElementById('app')!; // null なら実行時エラー
// ✅ 明示的な null チェック
const element = document.getElementById('app');
if (!element) throw new Error('Element not found');
// この行以降、element は HTMLElement 型
! は as より危険だ。ESLint の @typescript-eslint/no-non-null-assertion ルールで禁止できる。
as unknown as T (ダブルアサーション)
// ❌ 最も危険: 任意の型に変換できる
const num = 'hello' as unknown as number;
ダブルアサーションは型安全性を完全に破壊する。使用は絶対に避ける。
実務での活用方法は関連書籍にも詳しい。