我有一个具有payload
和type
属性的并集类型,其中type
是我们唯一的属性。给定type
时,我想推断出有效载荷类型。
type AAction = {type: 'A', payload: APayload};
type BAction = {type: 'B', payload: BPayload};
type APayload = number;
type BPayload = string;
type Actions = AAction | BAction;
const actions: Actions[] = [];
type PayloadOfType<T extends Actions['type']> = ????
type PayloadOfTypeA = PayloadOfType<'A'>;
因此目标是PayloadOfTypeA
等于APayload
(或number
)。
这可能吗?
答案 0 :(得分:1)
您可以使用条件类型Extract
:
type AAction = {type: 'A', payload: APayload};
type BAction = {type: 'B', payload: BPayload};
type APayload = number;
type BPayload = string;
type Actions = AAction | BAction;
const actions: Actions[] = [];
type PayloadOfType<T extends Actions['type']> = Extract<Actions, { type: T }>['payload']
type PayloadOfTypeA = PayloadOfType<'A'>;