TypescriptでObject.keys(data)をループ処理した時、keyの型がstringになったしまうときの対処法
※本ページはプロモーションが含まれています
Typescriptで型付けされたオブジェクトをObject.keys()でmapなどのループ処理をすると、keyの型がオブジェクトのキー名でなく、stringになってしまいます。
type Data = {
Windows: string;
Mac: string;
Linux: string;
}
const data = {
Windows: "control+l";
Mac: "command+l";
Linux: "control+l";
}
const res = Object.keys(data).map((key)=>{
retun key
})
上記コードだと、resの型はstring[]になってしまいます。
そこで、keyofを使うことで、オブジェクトの型のキーのいずれかをとるUnionTypeにすることで、ループ中のkeyに型付けできます。
それを配列にする。
型定義部分はこんな感じ。
(keyof Data)[]
型アサーションasで上書きし、た全体はこんな感じ。
type Data = {
Windows: string;
Mac: string;
Linux: string;
}
const data = {
Windows: "control+l";
Mac: "command+l";
Linux: "control+l";
}
const res = (Object.keys(data) as (keyof Data)[]).map((key)=>{
retun key
})
