获取对象的键的联合类型的方法是:
const person = {
infoA:{
name: 'frankA',
age: 10,
},
infoB:{
name: 'frankB',
age: 20,
}
}
type PersonKeys = keyof typeof person;
//结果 type PersonKeys = "infoA" | "infoB";
但是如果给person定义类一个索引类型之后就无法再获取对象的键的类型了
type PersonInfo = {
name: string;
age: number;
};
type Person = {
[key in string]: PersonInfo;
};
const person: Person = {
infoA: {
name: 'frank',
age: 10,
},
infoB:{
name: 'frankB',
age: 20,
}
};
type PersonKeys = keyof typeof person;
//结果 type PersonKeys = string;
我要怎么做才能获取和第一个例子一样的结果?
更新:目前的解决方法是使用 satisfies
关键字:
type PersonInfo = {
name: string;
age: number;
};
type Person = {
[key in string]: PersonInfo;
};
const person = {
infoA: {
name: 'frank',
age: 10,
},
infoB:{
name: 'frankB',
age: 20,
}
} satisfies Person;
type PersonKeys = keyof typeof person;
//结果 type PersonKeys = "infoA" | "infoB";