打字稿 - 基于对象字典的窄类型?

时间:2021-01-21 19:39:14

标签: typescript

请参阅下面的代码,我正在根据 dictionary 对象中的 type 属性选择从 input 运行的两个函数之一。

然而,由于结果是联合函数,Typescript 会抛出错误。

有人知道如何解决这个问题吗?

type typeA = {
  type: A
}

type typeB = {
  type: B
}

const dictionary = 
{
  A: function fA (input: typeA)...
  B: function fB (input: typeB)...
}

const input : typeA | typeB = XYZ;

const pickedFunc = dictionary[input.type]; // input.type === 'A' | 'B' (literal union)

pickedFunc(input) // <--- Error! "typeA | typeB" is not compatible with function of "typeof fA | typeof fB"


1 个答案:

答案 0 :(得分:-1)

这是不可能的,因为不会在运行时评估类型。到那时,打字稿代码已成为没有任何静态类型检查的 javascript。但是,您可以使用类型保护,您可以阅读有关此 here 的信息。