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