联合类型的通用打字稿:从其他属性中找出属性的类型

时间:2019-07-29 13:12:32

标签: typescript generics union-types

我有一个具有payloadtype属性的并集类型,其中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)。

这可能吗?

1 个答案:

答案 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'>;

相关问题