typescript - 重载不类型检查 body

标签 typescript types overloading

TypeScript 是否根本不检查函数体是否有函数重载? 以下编译,虽然它显然没有按照它声称的那样做:

function a(input: string): string
function a(input: number): number
function a(input: string | number): string | number {
  if (typeof input === "string") return 42
  return "banana"
}

我的第三个签名有问题吗?包罗万象的签名没有出现在结果类型中,我不知道没有它就可以声明函数的方法,任何尝试都会遇到 Overload 签名与函数实现不兼容。 错误。

typeof a = {
    (input: string): string;
    (input: number): number;
}

我会接受切换到更明确的相交类型:

type C = ((input: number) => number) & ((input: string) => string)

但我不明白如何在不使用重载语法的情况下实际创建满足它的函数,这看起来像是强制转换。我在 Overloaded function type in typescript 中问过这个问题问题。

编辑:第一个 block 是一个极简主义的人为示例。您可以使用以下方法对其进行测试:

const number: number = a(0)
console.log("number", typeof number, number)

输出数字字符串banana

const string: string = a("")
console.log("string", typeof string, string)

输出字符串编号42

编辑 2: 这不是 Overloaded function type in typescript 的副本,我问的是针对所有重载对函数实现进行类型检查,这个问题是关于用新函数实现重载类型。

最佳答案

Does TypeScript not check the function body against function overloads at all?

不,它不会根据重载声明检查主体。

如您所见,它检查实现签名是否与所有重载声明兼容;并检查正文是否符合实现签名;就这样。此外,在调用站点进行重载解析时不考虑实现签名。

强制实现与重载声明的一致性不是设计目标,至少我是这样解释 FAQ 中的这条语句的。 :

The rationale here is that since JavaScript does not have function overloading, you will be doing parameter checking in your function, and this your function implementation might be more permissive that what you would want your users to call you through.

关于typescript - 重载不类型检查 body ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52132520/

相关文章:

c++ - vfptr 中的 Visual C++ 方法以相反的顺序

javascript - Angular 2 i18n 动态/即时翻译

typescript - Twin.Macro(样式化组件)+ NextJS 中的 Typescript : Argument of type 'Interpolation<never>' is not assignable to parameter of type

javascript - 从哪里获得单个 lodash 包的@types?

Swift:用于类型检查的通用函数

haskell - 镜头的用途/用途是什么?

haskell - 使用数据种类对函数类型的约束

swift : Possible to overload randomVar as? [MyStruct]?

c++ - 非静态数据成员(数组)的使用无效

javascript - 避免在 array.from 中使用临时变量的一个衬垫?