Typescript 不强制使用函数参数中的类型

标签 typescript casting

我有一个非常简单的函数,它接受 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 执行类型检查。

不要将anyobject混淆,如果您使用的是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/

相关文章:

C++ Void 非指针

java - 错误: com. mysql.jdbc.JDBC4Connection无法转换为com.mysql.jdbc.Statement

node.js - 使用 cxsd 将 .xsd 转换为 TypeScript,cxsd 无法识别

javascript - Uncaught ReferenceError : exports is not defined at polyfills. js:17

typescript - 在 typescript 中指定本地 .d.ts 类型文件的目录

javascript - angular 6 自定义元素在 IE11 和 Firefox 上失败,出现语法和影子 dom 错误

将 double(不是指针)转换为 void 指针

c - 将 char 数组传递给 const void* 参数

c - 赋值使指针无需强制转换

angular - Response.json() 使用接口(interface)绑定(bind)到单个对象 - RxJs/Observable 失败