我有一个非常简单的函数,它接受 3 个整数,将它们加在一起并将总和打印到控制台。
function add(n1, n2, n3) {
var sum : number = n1 + n2 + n3;
console.log(sum);
}
我的假设是 sum
是一个整数,因此它强制类型匹配。所以我尝试了这个。
add(1,2,"Henok");
TypeScript 不会提示,它只是打印出 3Henok
。为什么?
在 toskv 的评论中回答,他提到了两件事
actually what you are writing there is var sum:number = (1 as any) + (2 as any) + ('hehe3' as any) because the types of the parameters are not specified and they default to any
为了强制执行编译时间提示,他添加了这个建议
you can enable the noImplicitAny option when compiling and tsc will complain that you have not properly typed your code.
这对我有用。谢谢托斯克夫。
最佳答案
参数还应该指定 typescript 中的类型,以便查看编译错误。
function add(n1:number, n2:number, n3:number) {
var sum : number = n1 + n2 + n3;
console.log(sum);
}
add(1,2, "Henok"); // compilation error
感谢托斯基
默认情况下,未标记任何类型的参数/变量被视为“any”,any 实际上是任何内容(任何类型),并且不会对 any 执行类型检查。
不要将any
与object
混淆,如果您使用的是C#之类的东西,那么any类似于dynamic
,其中类型由以下位置确定运行时。
所以,表达式
var sum:number = n1 + n2 + n3
实际上是
var sum:number = (n1 as any) + (n2 as any) + (n3 as any)
关于Typescript 不强制使用函数参数中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46566021/