有沒有辦法根據聯合中的鍵獲取聯合型別的特定成員,而無需明確定義聯合的每個成員?
type Thing = {
type: "person",
data: {
name: "John"
}
} | {
type: "building",
data: {
address: "111 Main Street"
}
}
type Person = Thing["where 'type' = 'person'"];
uj5u.com熱心網友回復:
您可以通過Distributive Conditional Types完成縮小范圍:
當條件型別作用于泛型型別時,當給定聯合型別時,它們變成分布式的。
然后我們使用型別T和的聯合never與相同的事實T
type NarrowUnion<T, N> = T extends { type: N } ? T : never;
type Person = NarrowUnion<Thing, 'person'>
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369881.html
標籤:打字稿
