typeofガード
| 対応: | TypeScript 1.0(2014) |
|---|
『typeof』ガードは、プリミティブ型を絞り込むための型ガードです。『typeof x === "string"』のように条件分岐を書くと、そのブロック内で TypeScript が変数の型を自動的に絞り込みます。
構文
typeof x === 'string' typeof x === 'number' typeof x === 'boolean' typeof x === 'bigint' typeof x === 'symbol' typeof x === 'undefined' typeof x === 'function' typeof x === 'object'
typeof が返す文字列一覧
| typeof の結果 | 対応する型 |
|---|---|
| 'string' | string |
| 'number' | number(NaN も含む) |
| 'boolean' | boolean |
| 'bigint' | bigint |
| 'symbol' | symbol |
| 'undefined' | undefined |
| 'function' | Function |
| 'object' | object・null・配列・その他オブジェクト(null に注意) |
サンプルコード
function format(value: string | number | boolean): string {
if (typeof value === 'string') {
// ここでは value: string
return value.toUpperCase();
} else if (typeof value === 'number') {
// ここでは value: number
return value.toFixed(2);
} else {
// ここでは value: boolean
return value ? 'yes' : 'no';
}
}
// undefined のチェック
function greet(name?: string): string {
if (typeof name === 'undefined') {
return 'Hello, guest!';
}
// ここでは name: string
return `Hello, ${name}!`;
}
// typeof 'object' は null も含むので注意
function processObj(val: object | null) {
if (typeof val === 'object' && val !== null) {
// ここでは val: object
console.log(Object.keys(val));
}
}
概要
『typeof』ガードは TypeScript が標準でサポートする型ナローイングの手法の一つです。JavaScript の『typeof』演算子をそのまま条件式で使うだけで型が絞り込まれるため、特別な設定は不要です。
注意点として、『typeof null === "object"』は JavaScript の仕様上 true を返します。null を弾きたい場合は『typeof val === "object" && val !== null』のように追加チェックが必要です。
クラスのインスタンスを絞り込む場合は instanceof ガード を、プロパティの存在で絞り込む場合は in 演算子ガード を使います。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。