0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScriptでのkeyofとtypeof演算子による強力な型操作

Last updated at Posted at 2024-04-09

keyof

keyof 演算子は対象のオブジェクトタイプ(Type)からキーを抽出し、文字列または数字のリテラルタイプ(Literal Type)で構成された新しいユニオン(Uniton Type)タイプを生成します。

type User = { name: string; age: number; 0: number; "1": string };
type UserKey = keyof User;

上のコードでは、UserKey型は"name" | "age" | 0 | "1"ユニオン型と同等です。これにより、Userオブジェクトのキーを安全に使用できます。

const userKey1: UserKey = "name"; // 正しい
const userKey2: UserKey = "age"; // 正しい
const userKey3: UserKey = 0; // 正しい
const userKey4: UserKey = "1"; // 正しい

// エラー: "gender"は'keyof User'型に割り当てることができません。
const userKey5: UserKey = "gender";

typeof

typeof 演算子は対象の変数(variable) またはプロパティ(property)に割り当てられた値と同じタイプを生成します。

let typeScript = "TypeScript";
type TypeScript = typeof typeScript;

上記のコードでは、TypeScript型はtypeScript変数に割り当てられた値の型、つまり文字列リテラル型"TypeScript"と同じです。typeofを使用すると、変数やオブジェクトの特定のプロパティの型を抽出して再利用できます。

const user = { name: "Aaron", age: 19 };
const age1: typeof user.age = 19; // 正しい
const age2: typeof user.age = "19"; // エラー: 文字列を数値型に割り当てることはできません。

結論

keyofとtypeof演算子は、TypeScriptの型システムを効率的に利用できる強力なツールです。これらを利用することで、開発者はより柔軟で再利用可能な型を定義でき、コードの安全性を高めつつ重複を減らすことができます。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?