如何仅使用预定义的可用键的一部分来创建类型?
我做类似的事情:
export type MyKeys = 'aa' | 'bb' | 'cc';
export type MyType = {
[k in MyKeys]: any;
};
并使用它:
let mySpecialObj: MyType = {
aa: 'key',
// bb: 'key', <-- without this for example
cc: 'key'
}
(其他问题:
如我所见,here的问题并不相同,因为我的意思是使用迭代器键声明的类型:[MyKeys中的k]:any; )
最佳答案
您可以将所有字段标记为可选:
export type MyKeys = 'aa' | 'bb' | 'cc';
export type MyType = {
[k in MyKeys]?: any;
};
let mySpecialObj: MyType = {
aa: 'key',
cc: 'key'
}
关于javascript - 如何仅使用预定义的可用键的一部分来创建类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50599911/