问题
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