我試圖從選項串列中為型別指定一個鍵名。使用我的方法似乎不需要所有選項作為鍵,這不是我想要的。我需要從選項串列中指定一個鍵名,而不需要實作所有選項。
型別 '{ a: number; 中缺少屬性 'b' }' 但需要在型別 '{ a: number; b:數量;}'。
type Options = 'a' | 'b';
type Widget = {
name: string,
foo: {
[key in Options]: number
}
}
const widget: Widget = {
name: 'foo',
foo: {
a: 1,
}
};
const anotherWidget: Widget = {
name: 'bar',
foo: {
b: 1,
}
};
操場
uj5u.com熱心網友回復:
使用可選欄位:
type Widget = {
name: string,
foo: { [key in Options]?: number }
}
或Partial<T>:
type Widget = {
name: string,
foo: Partial<Record<Options, number>>
}
如果您只接受一個且只有一個選項,請查看此答案以獲取完整圖片。這是簡單的方法:
type OneKey<T extends string, V> = { [T1 in T]: Record<T1, V> }[T]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377276.html
標籤:打字稿
