🦴

配列から型を生成してオブジェクトのKeyに指定する備忘録

2022/11/24に公開

何?

const USER_KEYS = ["name", "mail", "address", "tel"];

みたいなのから

type UserKeys = "name" | "mail" | "address" | "tel";

を生成してProfileみたいなオブジェクトのKeyに指定したいんです。毎回忘れるのでメモ。

どないするん

as constしてtypeof

const USER_KEYS = ["name", "mail", "address", "tel"] as const;

type UserKeys = typeof USER_KEYS[number];

なんでできるんかはこれが詳しそう
https://typescriptbook.jp/tips/generates-type-from-array

key in

const ksyunnnn: { [key in UserKeys]: string } = {} // 補完走る

https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
https://qiita.com/yuma84/items/72f72a2fff987d3de28a

Discussion