2017-08-12 57 views
-1

我有這樣的代碼打字稿類屬性的默認值不transpiled

class GameManager { 

    protected games: Game[]; 

    /** 
    * Clear the list from started games. 
    */ 
    clean(): void { 
    this.games = this.games.filter(game => !game.isRunning()); 
    } 
} 

每當我打電話clean()上一個新的實例,我得到

TypeError: Cannot read property 'filter' of undefined

如果我看transpiled代碼是沒有的定義一個屬性。

"use strict"; 
Object.defineProperty(exports, "__esModule", { value: true }); 
var GameManager = (function() { 
    function GameManager() { 
    } 
    /** 
    * Clear the list from started games. 
    */ 
    GameManager.prototype.clean = function() { 
     this.games = this.games.filter(function (game) { return !game.isRunning(); }); 

    return GameManager; 
}()); 
exports.default = GameManager; 

我還試圖限定的默認值作爲一個空數組,這是多餘的,但仍然

protected games: Game[] = []; 

這是沒有效果的。

我該如何告訴它定義數組而不必編碼構造函數?

回答

1

I also tried defining a default value as an empty array, which is redundant but still

這不是多餘的;這是必要的。未初始化的屬性值爲undefined,而不是[]

This had no effect

你沒有測試這個正確,你不知何故錯誤地調用的函數。前者最有可能。

+1

猜猜誰忘記了... facepalm。猜猜我應該刪除這個問題,不會真的對任何人有用。 –

0

您可以創建一個構造函數來初始化變量。

class GameManager { 
    constructor(games: Game[]) { 
     this.games = games; 

    } 

    protected games: Game[]; 



    ... 
} 

const manager = new GameManager(theGames); // initialize it to avoid the problems