隐式类型转换中的TypeScript错误 [英] TypeScript error on implicit type conversion

查看:58
本文介绍了隐式类型转换中的TypeScript错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使TypeScript在隐式类型转换上引发错误?在我看来,JavaScript中的所有隐式类型转换都是该语言中较大的bug来源之一,因此我想采用一种类似以下代码的方式:

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
}

让我知道它将是隐式的通过-运算符将函数类型转换为数字,从而始终返回 NaN

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

推荐答案

TypeScript允许这样做,因为它是有效的JavaScript。
您始终可以覆盖 toString()方法。

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

请考虑以下内容:

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

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

这篇关于隐式类型转换中的TypeScript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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