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

时间:2017-10-18 20:21:54

标签: 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?

基本上我希望TypeScript生成:

if(bar === void 0 || isNaN(bar)) bar = 0;

1 个答案:

答案 0 :(得分:2)

  

基本上我希望TypeScript生成

你必须自己写:

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