繁体   English   中英

通过添加新类型来检查区分联合的类型

[英]Type checking discriminated unions with adding new types

可以说我有以下打字稿类型:

enum EntityKind {
  Foo = 'foo',
  Bar = 'bar',
}

type Foo = {
  kind: EntityKind.Foo,
  foo: string
}

type Bar = {
  kind: EntityKind.Bar,
  bar: number
}

type Entity = (Foo | Bar) & {
  id: string,
  name: string
}

我想要的是能够在我的枚举中添加新类型时使类型检查器失败。 所以我希望的是:

enum EntityKind {
  Foo = 'foo',
  Bar = 'bar',
  Baz = 'baz',
}

我会得到一些错误,需要我定义一个新类型Baz并将其添加到联合。

这可能吗?

如果您希望类型Entity出现错误,您可以向需要EntityKind扩展EntityUnion['kind']的交集添加另一种类型:

enum EntityKind {
  Foo = 'foo',
  Bar = 'bar',
}

type Foo = {
  kind: EntityKind.Foo,
  foo: string
}

type Bar = {
  kind: EntityKind.Bar,
  bar: number
}
type Check<T, U extends T> = {}

type EntityUnion = Foo | Bar 
type Entity = EntityUnion & {
  id: string,
  name: string
} & Check<EntityUnion['kind'], EntityKind>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM