【问题标题】:Typescript function overloading: typescript does not analyze function codeTypescript函数重载:typescript不分析函数代码
【发布时间】:2020-06-01 20:33:07
【问题描述】:

考虑以下函数重载和带有错误的实现。

function foo(param: number): boolean;
function foo(param: string): string;

function foo(param) {
  if (typeof param === "number") {
    // typescript does not complain that 12 is not boolean
    return 12;
  } else if (typeof param === "string") {
    // typescript does not complain that {} is not string
    return {};
  }
}

以下是解释它的方式:

  1. 如果函数 foo 采用数字参数,它应该返回布尔值

  2. 如果函数foo接受字符串参数,它应该返回字符串

  3. 应该禁止其他调用

确定类型检查器可以通过分析功能代码来验证 1&2。 但是打字稿不这样做 - 它只做 3.

是否可以在打字稿中实现上述行为?

【问题讨论】:

标签: typescript overloading


【解决方案1】:

删除function foo(param)。这增加了第三个重载,param 键入为any

function foo(param: number): boolean;
function foo(param: string): string {
  if (typeof param === "number") {
    return 12;
  } else if (typeof param === "string") {
    return {};
  }
}

Code in TypeScript Playground

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 2021-11-20
    • 2016-10-27
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多