函数分配的类型检查,带有联合类型参数的函数

时间:2018-11-23 13:10:00

标签: typescript

此行产生错误“类型'string | number'不能分配给类型'string'”

const myVar: string = "test" as number | string;  // error, fine

那为什么没有错误呢?

const myFunc: (ns: number | string) => void = (n: number) => alert(n * 2);  // no error ???

回调在js / ts中经常使用,所以对我来说似乎很奇怪。 当前ts版本是3.1

1 个答案:

答案 0 :(得分:1)

在默认的编译器设置下,回调是双变量的,这意味着如果实现参数是声明参数的子类型,则允许分配。

这显然是类型系统中的一个大漏洞,该系统使用strict*选项(如本PR中所述的strictFunctionTypes)插入。如果启用此编译器选项,则分配将是错误的。

相关问题