TypeScript:如何在类型实参中定义可能的键的数组?

时间:2019-11-28 11:51:23

标签: typescript

我的计划是:

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
  }
}

Playground

问题是它确实会引发错误,但是它对key in T也是错误的。

因此,如果我用hobbies.racing定义Musician,也不会出错

有什么解决办法吗?

1 个答案:

答案 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">

Playground


要回答原始问题并使数组起作用:

type Hobbies <T extends Array<keyof typeof hobbies>> = {
  [key in T[number]]: number
}

请注意key in T[number]-键位于数组值上

Playground