2015-12-30 140 views
2

我想在TypeScript中創建一個字典中的每個元素都是類類型的字典。TypeScript創建一個類型的字典

interface Methods { 
    [index: string]: MethodRep; 
} 

export class MethodRep { 
    name: string; 
} 

export class BaseFileStructure { 
    public methods: Methods; 

    constructor() { 
     this.methods = {}; 
    } 
} 

但它似乎並不喜歡它。我使用原子與TypeScript插件。它說Compile failed but emit succeeded

如果我改變元素的字符串,然後它工作(即使把型號不工作)

interface Methods { 
    [index: string]: string; // only this works 
} 

什麼我在這裏失蹤的類型?

+2

Typescript playground(http://www.typescriptlang.org/Playground)不會爲您的代碼顯示任何錯誤。 – TSV

+0

您是否嘗試將您的MethodRep類更改爲接口? – Guillaume

+0

同意@Guillaume我只有這樣才能使用接口 – gsobocinski

回答

0

你可以嘗試更換MethodRep類的接口是這樣的:

interface Methods { 
    [index: string]: MethodRep; 
} 

export interface MethodRep { 
    name: string; 
} 

export class BaseFileStructure { 
    public methods: Methods; 

    constructor() { 
     this.methods = {}; 
    } 
} 
1

由於interface Methods不外傳,但你使用它作爲出口,如果你的編譯器是一個類的一部分設置爲創建聲明(d.ts)文件(並且可能您所使用的插件總是在後臺執行此操作並管理自己寫入這些文件),TypeScript將會抱怨接口方法未被導出,因爲它被引用可公開訪問的成員:

錯誤TS4031:導出類的公共屬性「方法」已經或正在使用專用名稱「方法」。

如果更改interface Methodsexport interface Methods,這應該解決的問題,因爲否則你的代碼沒有問題。