![](/img/trans.png)
[英]How to create a sub type with values specified for some fields and eliminate optional member in typescript
[英]How to define a type with some optional specified properties along side some required specified ones in Typescript
我有以下 object:
const colors: tColors = {
dark: {
main: {
normal: '#022c43', dark30: '#011f2f', light30: '#4e6b7b', contrastColor: '#fff',
},
secound: {
normal: '#053f5e', dark30: '#042c42', light30: '#add6de', contrastColor: '#fff',
},
error: { normal: '#d32f2f', contrastColor: '#fff' },
success: { normal: '#388e3c', contrastColor: '#fff' },
},
light: {
main: {
normal: '#28527a', dark30: '#1c3955', light30: '#6986a2', contrastColor: '#fff',
},
secound: {
normal: '#8AC4D0', dark30: '#618992', light30: '#50798e', contrastColor: '#fff',
},
error: { normal: '#e57373', contrastColor: '#000' },
success: { normal: '#81c784', contrastColor: '#000' },
},
};
我將tColors
定義為:
type tColors = {
[themeKey in 'light' | 'dark']: {
[key : string]: {
[shadeKey: string ]: string
}
}
};
它有效,但如果我想像這樣限制shadeKey
:
shadekey in 'normal' | 'dark30' | 'light30' | 'contrastColor'
它給了我一些關於error
和success
字段的錯誤,錯誤是:
Type '{ normal: string; contrastColor: string; }' is missing the following properties from type '{ normal: string; dark30: string; light30: string; contrastColor: string; }': dark30, light30
問題是我不想在error
和success
字段中添加dark30
或light30
但我希望shadekey
對其他鍵敏感
有什么辦法可以將dark30
和light30
設置為可選屬性,但它們的rest保持不變?
由於shadeKey
值是已知且有限的,您可以將它們寫為屬性而不是索引簽名:
type tColors = {
[themeKey in "light" | "dark"]: {
[key: string]: {
normal: string;
dark30?: string;
light30?: string;
contrastColor: string;
};
};
};
在這里?
在dark30
和light30
之后表明該屬性是可選的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.