2015-12-30 139 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,这应该解决的问题,因为否则你的代码没有问题。