基于另一个键的值的条件类型

时间:2019-06-03 18:31:43

标签: javascript typescript

有没有一种方法可以使用基于另一个键的值的接口?

因此,如果options等于特定值,我希望driver使用特定接口:

  • 如果driver == 'a'使用InterfaceA
  • 如果driver == 'b'使用InterfaceB

我认为类似的方法可能有效,但无效。

export interface InterfaceA {}
export interface InterfaceB {}

export interface MyInterface {
  driver: string
  root: string
  options: driver == 'a' ? InterfaceA : InterfaceB
}

1 个答案:

答案 0 :(得分:1)

有几种不同的方法可以做到这一点,但是我倾向于采用这种方法,因为它使我最容易阅读错误消息:

export interface InterfaceA {}
export interface InterfaceB {}

type MyInterfaceA = {
  driver: 'a',
  root: string,
  options: InterfaceA,
}
type MyInterfaceB = {
  driver: 'b',
  root: string,
  options: InterfaceB,
}
export type MyInterface = MyInterfaceA | MyInterfaceB;

据我所知,它们必须是type而不是interface,因为接口不支持联合类型。 (谢谢@jcalz)。

可以在不复制root属性的情况下编写上面的代码,如果有更多通用属性,这很有用,但是我最终还是复制了所有内容,因为在避免嵌套的并集和相交时,错误消息更加清晰了