使用类型检查来区分联合类型并添加新类型

3
假设我有以下 TypeScript 类型:
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并将其添加到联合中,否则会出现一些需要这样做的错误。

这种操作是否可行?

1个回答

1
如果您想在类型 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接