假設我有這些型別:
interface A {
a: number
b: string
c: string
}
interface B {
a: string
b: string
}
type C = A | B
我想獲取 type 的可能值C
。例如
type ValueOfObject<T, K> = What should be here?
type aValues = ValueOfObject<C, 'a'> // should return number | string
type bValue = ValueOfObject<C, 'b'> // should return string
type cValues = ValueOfObject<C, 'c'> //should return string | undefined
我怎樣才能實作它?
我設法通過以下方式從聯合中獲取所有密鑰
type KeysOfUnion<T> = T extends T ? keyof T: never;
雖然無法獲取值
uj5u.com熱心網友回復:
你可以這樣做:
type KeysOfUnion<T> = T extends T ? keyof T: never;
type ValueOfObject<T, K extends KeysOfUnion<T>> =
T extends infer U
? K extends keyof U
? T[K]
: undefined
: never
我們分配T
條件并檢查每個成員U
if K extends keyof U
。如果是,我們可以回傳T[K]
,如果不是,我們添加undefined
到聯合中。
操場
uj5u.com熱心網友回復:
我找到了解決方案:
type KeysOfUnion<T> = T extends T ? keyof T: never;
// We need to convert our union to intersection then our type would be trivial
type UnionToIntersection<T> =
(T extends any ? (x: T) => any : never) extends
(x: infer R) => any ? R : never;
type UnionValue<U, K extends KeysOfUnion<U>> = UnionToIntersection<U>[K];
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527577.html
標籤:打字稿类型