[英]Type checking discriminated unions with adding new types
Lets say I have the following typescript 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
}
What I want is to be able to have the type checker fail when I add a new type to my enum. 我想要的是能够在我的枚举中添加新类型时使类型检查器失败。 So what I'm hoping for is: 所以我希望的是:
enum EntityKind {
Foo = 'foo',
Bar = 'bar',
Baz = 'baz',
}
and I would get some kind of error that would require me to define a new type Baz and add it to the union. 我会得到一些错误,需要我定义一个新类型Baz并将其添加到联合。
Is this possible? 这可能吗?
If you want an error in the type Entity
you could add another type to the intersection that requires EntityKind
to extend EntityUnion['kind']
: 如果您希望类型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.