Typescript,如何从另一个属性值推断类型?

phi*_*ilo 7 typescript

例如,我有一个带有属性的接口:keyvalue,我想通过键推断值类型。

interface Obj { a: number; b: string }

interface Param<K extends keyof Obj> {
  key: K
  value: Obj[K] // I want to infer this type
}

const p: Param<keyof Obj> = {
  key: 'a',
  value: '', // typescript can't infer this type, expect number
}

Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

Nic*_*las 4

Obj[K]表示可以Obj通过 中的任何值K(而不仅仅是其中的值)进行索引来获取的值key

因此,要使用此结构,您需要指定更紧密地使用哪个键:

interface Obj { a: number; b: string }

interface Param<K extends keyof Obj> {
  key: K
  value: Obj[K]
}

const p: Param<'a'> = { // changed line
  key: 'a',
  value: '', // error
}
Run Code Online (Sandbox Code Playgroud)

遗憾的是,无法推断通用参数。


如果您已经知道 中的内容Obj,可能有更好的方法来做到这一点。

interface AParam {
    key: 'a'
    value: number
}

interface BParam {
    key: 'b'
    value: string
}

type Param = AParam | BParam;

const p: Param = {
  key: 'a',
  value: '', // error
}
Run Code Online (Sandbox Code Playgroud)

如果您需要变量p能够保存其中任何一个key,但仍然具有value正确的类型,这是唯一可行的方法。