函数参数类型约束无效?

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

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

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

阅读 3.5k
2 个回答

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

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

clipboard.png

但是还是会把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.

新手上路,请多包涵

const 换成let

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进