打字稿中的通用类型级别方案

时间:2018-07-19 14:43:52

标签: typescript discriminated-union conditional-types

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

这里是一个例子:

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
    }
}

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

谢谢。

0 个答案:

没有答案