TypeScript error on implicit type conversion

戏子无情 提交于 2019-12-12 18:27:43

问题


Is there a way to make TypeScript throw an error on an implicit type conversion? Seems to me like all the implicit type conversions in JavaScript are one of the larger sources of bugs in the language, so I'd like a way for something like the following code:

let h = (n: number): number => {
    let f = () => 0 
    return -f
}

to let me know it will be implicitly converting the function type to a number via the - operator, and thus always returning NaN.


回答1:


TypeScript allows this because it is valid JavaScript. You can always override the toString() method.

Consider the following:

let x = {}
x.toString = () => "1"
ley y = -x  // -1

let f = () => { }
f.toString = () => "1"
let z = -f // -1


来源:https://stackoverflow.com/questions/47361859/typescript-error-on-implicit-type-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!