TypeScriptを使っていると、typeof
演算子(JavaScriptにも存在する)によく遭遇します。TypeScriptでtypeofは
二つの文脈で使われます。
- JavaScriptの実行時の
typeof
演算子 - TypeScriptの型演算子としての
typeof
1.JavaScriptのランタイムtypeof演算子としてのtypeof
typeofは
被演算子のデータ型を表す文字列を返します。
let value = "hello";
console.log(typeof value); // "string"
let number = 32;
console.log(typeof number); // "number"
let func = () => {};
console.log(typeof func); // "function"
返される値はJavaScriptの基本データ型(boolean, number, bigint, string, symbol, null, undefined)とfunction, objectです。
2.TypeScriptの型演算子 typeof
TypeScriptではtypeofを
type
コンテキストでも使うことができます。この場合、役割が変わります。
const user = { typeof
name: "John"、
age: 30、
isAdmin: true
を指定します;}
const v_user = typeof user; // object
type User = typeof user;
// 結果
// type User = {
// name: string;
// age: number;
// isAdmin: boolean;
// }
上の例のv_userは
const
キーワードで宣言された変数で使われました。従って、値が代入されなければならないので、userの
ランタイムのタイプを指す'object
'を返します。しかし、type
キーワードの後ろに使われたtypeofは
タイプスクリプトのタイプを返します。
typeofは
値から型を抽出する時だけ使うようにします。すでに型であるものから使う時はエラーが出ます。
// 間違った使い方
type MyString = string;
type Wrong = typeof MyString; // エラー!
// 正しい使い方
const myString = "hello";
type Correct = typeof myString; // string
typeofの活用
1.配列からユニオン型の抽出
const colors = ["red", "green", "blue"] as const;
type Colors = typeof colors[number];
// type Colors = "red" | "green" | "blue"
2.オブジェクトタイプの抽出
// without as const
const config = { const
endpoint: "api.example.com"、
port: 3000
};
type Config = typeof config;
// type Config = {
// endpoint: string;
// port: number;
// }
// with as const
const config = { { const config
endpoint: "api.example.com"、
port: 3000
} as const;
type Config = typeof config;
// type Config = {
// readonly endpoint: "api.example.com";
// readonly port: 3000;
// }
as constと
一緒に使うとreadonlyが
付与されて抽出されます。
3.関数タイプ抽出
ユーティリティタイプのReturnTypeと
Parametersを
活用して関数のパラメータと戻り値のタイプを抽出することができます。
function createUser(name: string, age: number) { return { id: Date.now() { id: Date.now()
return { id: Date.now(), name, age };
}; }
type User = ReturnType<typeof createUser>;
// type User = {
// id: number;
// name: 文字列;
// age: number;
// }
type Param = Parameters<typeof createUser> // type Param = { type Param = { type of createUser
// type Param = {
// name: 文字列;
// age: number;
// }
🔎 参照