Typescript函数重载:typecript不分析函数代码。

问题描述 投票:0回答:1

考虑下面的函数重载和实现有bug。

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,但typescript不这样做--它只做3。

有没有可能在typescript中实现上述行为?

typescript overloading
1个回答
0
投票

移除 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 {};
  }
}

TypeScript Playground中的代码

© www.soinside.com 2019 - 2024. All rights reserved.