使用枚举作为联合中的文字类型的打字稿

时间:2021-04-13 14:41:39

标签: typescript enums union-types

我想创建一个根据成员值而变化的类型。联合类型来救援:

type SomeType = {
  method: 1,
} | {
  method: 2 | 3,
  someAdditionalData: number,
}

这很好用,如果方法是文字数1,则不需要someAdditionalData,如果是 2 或 3,则不需要。
但是,文字有一些含义,并且要编码我想使用枚举:

enum Method {
  One = 1,
  Two = 2,
  Three = 3,
}

type SomeType = {
  method: Method.One,
} | {
  method: Method.Two | Method.Three,
  someAdditionalData: number,
}

不幸的是,这似乎破坏了输入信息:

const someThing: SomeType = {
  method: Method.Two
}

不会导致我的 IDE 或 TS 编译器发出警告。

有什么想法可以奏效,还是我做错了什么?如果这不受支持,那么处理这种情况的好方法是什么(假设您需要 method 的最终实现是一个数字并希望通过命名参数对其进行寻址)?

这是 TS 4.1。

编辑:一个相当好的解决方案是定义一个对象而不是一个枚举,例如:

const Method = {
  One: 1 as 1,
  Two: 2 as 2,
  Three: 3 as 3
}

type SomeType = {
  method: typeof Method.One,
} | {
  method: typeof Method.Two | typeof Method.Three,
  someAdditionalData: number,
}

这将确保正确的类型信息,但与在原始问题中使用枚举并不严格相同。

0 个答案:

没有答案