首页 > 解决方案 > 打字稿:如何在类型参数中定义一组可能的键?

问题描述

我的计划是:

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 就不会出错

有什么解决方案吗?

标签: typescript

解决方案


没有严格回答问题,但您可以使用联合类型而不是数组:

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]- 键在数组值上

操场


推荐阅读