【问题标题】:Typescript - narrow type based on object dictionary?Typescript - 基于对象字典的窄类型?
【发布时间】:2021-01-22 23:21:11
【问题描述】:

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

但是,由于结果是联合函数,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"


【问题讨论】:

  • 能否填写函数定义和XYZ,使示例代码是有效的TypeScript?
  • 我不太确定如何,XYZ 的意思是表示一段未知的代码(例如通用输入参数)。所以基本上任何具有“类型”属性的对象都是 A 或 B。
  • AB 以上类型,还是应该是'A''B'?我对你想要做什么感到有点困惑
  • 基本上,我正在尝试根据输入中的type 参数从dictionary 中选择要运行的正确函数。
  • 请考虑修改此处的代码以构成 minimal reproducible example 适合放入像 The TypeScript Playground 这样的独立 IDE 中,其中唯一存在的问题是您要询问的问题。这将使想要帮助您的人开始尝试解决或解决问题,而不是首先花费时间和精力来试图证明问题。这也将提高您收到的任何答案将首先被测试的几率。祝你好运!

标签: typescript


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2012-11-17
    • 1970-01-01
    • 2019-04-03
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多