首页 > 解决方案 > 打字稿中的通用类型级别方案

问题描述

我想为函数创建一个输入和输出类型的标记方案,以便将标记传递给函数,它将推断输入和输出类型。

这是一个例子:

type Aa = {
    tag: 'a',
    a: 2
}

type Ab = {
   tag: 'b',
   a: 3
}

type TInputMap = {
    'a': Aa,
    'b': Ab
}

type TResultMap = {
    'a': string,
    'b': number
}

type A = Ab | Aa;

const fn = <TAction extends keyof TInputMap>(type: TAction, action: TInputMap[TAction]): TResultMap[TAction] => { 
    if (type === 'a') {
      action.a // expected to be 2, but inferred as 2 | 3
    }
}

有可能吗?也许使用条件类型?

谢谢。

标签: typescriptdiscriminated-unionconditional-types

解决方案


推荐阅读