我的计划是:
enum hobbies {
music = 'music',
sports = 'sports'
}
type Hobbies <T extends Array<keyof typeof hobbies>> = {
[key in T]: number
}
type Musician = {
hobbies: Hobbies<["music"]>
}
type Racer = {
hobbies: Hobbies<["racing"]> //errors, fine
}
const musician: Musician = {
hobbies: {
music: 2,
racing: 1 //should error but it doesn't
}
}
问题是它确实会引发错误,但是它对key in T
也是错误的。
因此,如果我用hobbies.racing定义Musician,也不会出错
有什么解决办法吗?
答案 0 :(得分:1)
并非严格回答问题,但是您可以使用union type代替数组:
enum hobbies {
music = 'music',
sports = 'sports'
}
type Hobbies <T extends keyof typeof hobbies> = {
[key in T]: number
}
type Musician = {
hobbies: Hobbies<"music">
}
type Racer = {
hobbies: Hobbies<"racing"> //errors, fine
}
const musician: Musician = {
hobbies: {
music: 2,
racing: 1 //now errors
}
}
要指定多个允许的键,只需使用联合类型:
hobbies: Hobbies<"music" | "sports">
要回答原始问题并使数组起作用:
type Hobbies <T extends Array<keyof typeof hobbies>> = {
[key in T[number]]: number
}
请注意key in T[number]
-键位于数组值上