2017-06-19 49 views
0

我想在TypeScript中初始化一個接口。無法在TypeScript中設置未定義的屬性XXX

export interface TestGroup { 
    "id": number; 
    "type": TestType; 
    "interval"?: number; 
} 


import {TestGroup} from "../../gen/api"; 
public functionConfig: TestGroup; 
. 
. 
. 
this.functionConfig.id = testGroup.functionTestConfig; 

我得到這個錯誤:

TypeError: Cannot set property 'id' of undefined

你能幫幫我嗎?

+0

需要functionConfig初始化爲某個值,現在它是undefiend,你最終會做undefined.id這是無效的JavaScript。 – toskv

+0

這是什麼? 'this.functionConfig'集合在哪裏?我們應該猜測? – Amy

+0

那麼你聲明'functionConfig',但你不給它任何值,因此它是未定義的。如果你做了'this.functionConfig = {test:「value」}'或者甚至只是'this.functionConfig = {}'就會被定義,所以之後你可以做'this.functionConfig.id =「whatever」 ' –

回答

1

您的functionConfig有一個類型,但它實際上是undefined。所以,你需要初始化:

public functionConfig: TestGroup = {id: 0, type: 'YourTestTypeHere'}; 

或您的默認值是

評論

var activateOnWeekDay: Array<boolean> = []; 
+0

非常感謝。你能告訴我:當我有一個像「activateOnWeekDay」這樣的變量時,我如何初始化Array :Array ; – Sohrab

+0

請參閱編輯部分。你只需要分配一個空數組 –

相關問題