簡體   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