【问题标题】:Typescript generic of union type: find out type of property from other property联合类型的打字稿泛型:从其他属性中找出属性的类型
【发布时间】:2019-07-29 21:20:10
【问题描述】:

我有一个带有payloadtype 属性的联合类型,其中type 我们是uniq。我想在给定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)。

这可能吗?

【问题讨论】:

    标签: typescript generics union-types


    【解决方案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'>;
    
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 2021-12-30
      • 2021-12-06
      • 2022-01-01
      • 2021-09-29
      • 1970-01-01
      • 2020-04-12
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多