如果现在我有一个数组keys
:
const keys = ['firstname', 'lastname']
我可以像下面这样将所有项映射为NewType
的键吗?
type NewType = {
firstname: any
lastname: any
}
首先你需要使用as const
语法告诉TS你的数组值不会改变:
const keys = ['firstname', 'lastname'] as const;
然后你可以从数组值创建一个联合类型:
type Union = typeof keys[number]; // type Union = "firstname" | "lastname"
然后使用映射类型创建NewType,如下所示:
type Obj = {
[k in Union]: any;
}
// type Obj = {
// firstname: any;
// lastname: any;
// }
const obj: Obj = {
firstname: '',
lastname: ''
}