Closed1

【TypeScript】keyof

seiya2130seiya2130
  • オブジェクトのプロパティを文字列型のユニオン型として返す
  • プロパティを変更したときに自動的にユニオン型も変更されるため保守性が向上する
  • プロパティ名を取得したループ処理などに使用される
type Person = {
  name: string;
  age: number;
};

type PersonKey = keyof Person;

const name: PersonKey = 'name';
const age: PersonKey = 'age';
// 型 '"sex"' を型 'keyof Person' に割り当てることはできません。のエラー
const sex: PersonKey = 'sex';

https://typescriptbook.jp/reference/type-reuse/keyof-type-operator

このスクラップは6ヶ月前にクローズされました