typescript - 函数参数类型约束无效?

查看:389
本文介绍了typescript - 函数参数类型约束无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

const add = function(x: number, y: number): number {
    return x + y;
};

console.log(add('hello', 5));

本意是只接受输入数字,可是传递字符串还是可以编译并执行最终的js代码,哪里出问题了?

解决方案

这是TypeScript? 如果有类型错误时,使用tsc编译时会报错:


我用VsCode写的也会提示错误:

但是还是会把ts文件编译成js文件,TypeScript只是帮你找出安全隐患。

TS官网的原话:
Notice that although there were errors, the greeter.js file is still created. You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.

这篇关于typescript - 函数参数类型约束无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆