繁体   English   中英

打字稿:声明空类对象

[英]Typescript: declare empty class object

是否可以从没有默认值的类中声明对象?

我有一堂课,看起来像下面;

export class Month {
 January: string;
 February: string;
 March: string;
 ...
}

mapMyPayload(specialMonths: Birthdays) {
 let myMonth = new Month;
 console.log(myMonth); //=> Month {}
    // here I expect the Object.keys(myMonth) 
    // returns {January=undefined, February=undefined, ...}
    // since I assume the new Month 
    // declares the myMonth as an object with undefined as its value
 Object.keys(myMonth).forEach(m => {
    // iterate thru the keys 
    // check if the month exists inside the specialMonths
    // and is not null or undefined
  if (specialMonths[m] != null) { 
   myMonth[m] = specialMonths[m];
 );
 return myMonth;
}

我想要实现的是检查对象中是否有任何undefined或为null并返回此类。

我查看了许多示例代码和文档,无论您具有隐式构造函数还是显式构造函数,都可以使用类名的new infront声明新类,但之后它们声明一些值。 因此,我认为实例在某些外部范围声明之前不存在。

class Foo {
  a: string;
  b: string;
  c: number;
}

var foo = new Foo();
console.log(foo.a); //undefined

更新:转换为以下JS代码:

var Foo = /** @class */ (function () {
    function Foo() {
    }
    return Foo;
}());
var foo = new Foo();
console.log(foo.a);

您的对象没有任何键,因为它们尚未定义,因此它们求助于“ undefined”文字,而不是“ undefined”作为值。 您可以尝试按照默认值“ undefined”作为代码行:

class Foo {
  a: string = undefined;
  b: string = undefined;
  c: number = undefined;
}

var foo = new Foo();
console.log(foo.a); //undefined
console.log(foo); //=> Foo{a: undefined, b: undefined, c: undefined}
Object.keys(foo).forEach(property => console.log(property));
// keys log as empty and not undefined

这会转换为以下JS:

var Foo = /** @class */ (function () {
    function Foo() {
        this.a = undefined;
        this.b = undefined;
        this.c = undefined;
    }
    return Foo;
}());
var foo = new Foo();
console.log(foo.a); //undefined
console.log(foo); //=> Foo{a: undefined, b: undefined, c: undefined}
Object.keys(foo).forEach(function (property) { return console.log(property); });
// keys log as empty and not undefined as part of the forEach loop

我个人不建议这种实现,因为它易于发生意外行为,并且与打字稿带来的JS的静态类型版本背道而驰。

也许如果您要详细说明要实现的目标,我们可以为您提供更好的解决方案?

为什么不可能呢?

如果不这样指定默认值,则类中的字段和属性将设置为默认值,对于字符串,则为null。

export class Month {
   January: string = "Something";
   February: string = "Something";
   March: string = "Something";
   ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM