TypeScriptのtypeof演算子

🌐

この記事は DeepL によって翻訳されました。誤訳があれば教えてください!

TypeScriptを使っていると、typeof演算子(JavaScriptにも存在する)によく遭遇します。TypeScriptでtypeofは二つの文脈で使われます。

  1. JavaScriptの実行時のtypeof演算子
  2. TypeScriptの型演算子としてのtypeof

1.JavaScriptのランタイムtypeof演算子としてのtypeof

typeofは被演算子のデータ型を表す文字列を返します。

let value = "hello"console.log(typeof value); // "string"

let number = 32console.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: 30isAdmin: 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 = stringtype Wrong = typeof MyString; // エラー!

// 正しい使い方
const myString = "hello"type Correct = typeof myString; // string

typeofの活用

1.配列からユニオン型の抽出

const colors = ["red", "green", "blue"] as consttype 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 consttype 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;
// }

🔎 参照