我有陣列: const arr = ['foo', 'bar', 'bax'];
我想基于陣列條目創建一個物件:
const obj = {
foo: true,
bar: true,
bax: false,
fax: true, // typescript should show error here because "fax" is not in "arr"
};
如何告訴打字稿所有的鍵都obj必須在里面arr?
uj5u.com熱心網友回復:
你可以這樣做:
const arr = ['foo', 'bar', 'bax'] as const;
type MappedObject = Record<typeof arr[number], boolean>;
const obj: MappedObject = {
foo: true,
bar: true,
bax: false,
fax: true, // typescript should show error here because "fax" is not in "arr"
};
打字稿游樂場
相關的 GitHub 問題 - Microsoft/TypeScript#28046
uj5u.com熱心網友回復:
const arr = ['foo', 'bar', 'bax'];
//I want to create an object based on array entries:
const obj = {
foo: true,
bar: true,
bax: false,
fax: true, // typescript should show error here because "fax" is not in "arr"
};
for(const [key, value] of Object.entries(obj))
{
if(!arr.includes(key))
{
console.log(`error, ${key}: ${value} not found in array`)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/373482.html
標籤:javascript 打字稿
