TypeScript-用于NaN检查的构造函数表达式

TypeScript-用于NaN检查的构造函数表达式,typescript,Typescript,在TypeScript中,我们可以使用默认值构建构造函数,如下所示: class Foo { constructor(public bar: number = 0) { // this.bar is 0 if constructed with no arguments. } } TypeScript生成以下命令: if(bar === void 0) bar = 0; 有没有一种方法可以声明一个简写语法,以类似的方式防止分配NaN 基本上,我希望TypeScr

在TypeScript中,我们可以使用默认值构建构造函数,如下所示:

class Foo {
    constructor(public bar: number = 0) {
        // this.bar is 0 if constructed with no arguments.
    }
}
TypeScript生成以下命令:

if(bar === void 0) bar = 0;
有没有一种方法可以声明一个简写语法,以类似的方式防止分配NaN

基本上,我希望TypeScript生成:

if(bar === void 0 || isNaN(bar)) bar = 0;
基本上,我希望TypeScript生成

你必须自己写:

class Foo {
    constructor(public bar: number = 0) {
        if (isNaN(bar)) this.bar = 0;
    }
}

哎呀,没有办法自动做到这一点。正如您所说,速记语法是一种仅在省略参数时才为其指定默认值的方法。如果包含,则必须手动检查不需要的值。哦,而且
bar===NaN
始终为false,请改用函数
isNaN(bar)
。@CRice更新为包含
isNaN(bar)
Number。isNaN
应用于检查
NaN
值。@zerkms为什么
Number.isNaN
vs
isNaN
<代码>isNaN(未定义);//true
编号.isNaN(未定义);//false
为什么要更改签名并手动执行
未定义的检查?@zerkms这样它就不会分散在两个地方。更新以尽可能多地保留原始代码。我刚刚意识到,对于ES2015目标,它甚至不会发出未定义的检查,是吗?@basarat有没有一种方法可以使用decorators检查NaN,即
构造函数(@CheckNaN value:number){…}