TypeScript 创建某个类型的字典

TypeScript create a dictionary of a type

本文关键字:字典 类型 创建 TypeScript      更新时间:2023-09-26

我正在尝试在TypeScript中创建一个字典,其中字典中的每个元素都是类类型。

interface Methods {
    [index: string]: MethodRep;
}
export class MethodRep {
    name: string;
}
export class BaseFileStructure {
    public methods: Methods;
    constructor() {
        this.methods = {};
    }
}

但它似乎不喜欢它。我正在使用带有TypeScript插件的atom。它说Compile failed but emit succeeded.

如果我将元素的类型更改为字符串,那么它可以工作(即使输入类型编号也不起作用(

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

我在这里错过了什么?

由于interface Methods没有导出,但您将其用作导出类的一部分,如果您的编译器设置为创建声明 (d.ts( 文件(并且您使用的插件可能总是在幕后执行此操作并自行管理这些文件的编写(,TypeScript 会抱怨接口 Methods 未导出,因为它被可公开访问的成员引用:

错误 TS4031:导出类的公共属性"方法"具有或正在使用私有名称"方法"。

如果将interface Methods更改为 export interface Methods ,这应该可以解决问题,因为否则您的代码没有问题。

你能尝试将MethodRep类替换为这样的接口吗:

interface Methods {
    [index: string]: MethodRep;
}
export interface MethodRep {
    name: string;
}
export class BaseFileStructure {
    public methods: Methods;
    constructor() {
        this.methods = {};
    }
}