[英]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.