简体   繁体   English

打字稿不使用函数参数强制执行类型

[英]Typescript not enforcing type with in function parameter

I have this very simple function that accept 3 integers, add them together and print the sum out to a console.我有一个非常简单的函数,它接受 3 个整数,将它们加在一起并将总和打印到控制台。

function add(n1, n2, n3) {
    var sum : number = n1 + n2 + n3;

    console.log(sum);
}

My assumption was sum is an integer therefore it enforce the type matching.我的假设是sum是一个整数,因此它强制执行类型匹配。 So i tried this.所以我尝试了这个。

add(1,2,"Henok");

TypeScript does not complain, it simply print out 3Henok . TypeScript 没有抱怨,它只是打印出3Henok Why?为什么?


Answered in the comment blow by toskv he mentioned two thing 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实际上你写的是 var sum:number = (1 as any) + (2 as any) + ('hehe3' as any) 因为没有指定参数的类型,它们默认为 any

and to enforce compile time complaining he add this suggestion并强制编译时间抱怨他添加了这个建议

you can enable the noImplicitAny option when compiling and tsc will complain that you have not properly typed your code.您可以在编译时启用 noImplicitAny 选项,tsc 会抱怨您没有正确键入代码。

That works for me.这对我行得通。 thank you toskv.谢谢你。

Parameter also should specify type in typescript in order to see compilation error.参数还应在打字稿中指定类型以查看编译错误。

function add(n1:number, n2:number, n3:number) {
    var sum : number = n1 + n2 + n3;

    console.log(sum);
}

add(1,2, "Henok"); // compilation error

Thanks to tosky感谢托斯基

By default parameters/variables that are not marked with any type are considered as "any" , any is literally anything (any type) and no type check is performed on any.默认情况下,未标记任何类型的参数/变量被视为 "any" , any 字面上是任何(任何类型),并且不会对 any 执行类型检查。

Don't confuse any with object , if you are using something like C# then any is similar to dynamic where type is determined at runtime.不要将anyobject混淆,如果您使用的是 C# 之类的东西,那么 any 类似于dynamic ,其中类型是在运行时确定的。

So, expression所以,表达式

var sum:number = n1 + n2 + n3

is actually实际上是

var sum:number = (n1 as any) + (n2 as any) + (n3 as any)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM