developer82
developer82

Reputation: 13713

TypeScript create a dictionary of a type

I'm trying to create a dictionary in TypeScript where each element in the dictionary is of a class type.

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

export class MethodRep {
    name: string;
}

export class BaseFileStructure {
    public methods: Methods;

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

but it doesn't seem to like it. I'm using atom with a TypeScript pluging. it says Compile failed but emit succeeded.

If I change the type of the elements to string then it works (even putting type number doesn't work)

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

what am I missing here?

Upvotes: 2

Views: 621

Answers (2)

C Snover
C Snover

Reputation: 18766

Since interface Methods is not exported, but you are using it as part of a class that is exported, if your compiler is set up to create declaration (d.ts) files (and it’s possible that the plugin you are using always does this behind the scenes and manages writing these files itself), TypeScript will complain that the interface Methods is not exported because it is referenced by a publicly accessible member:

error TS4031: Public property 'methods' of exported class has or is using private name 'Methods'.

If you change interface Methods to export interface Methods, this should solve the problem, since there is otherwise no problem with your code.

Upvotes: 1

Guillaume
Guillaume

Reputation: 844

Can you try with replacing MethodRep class to an interface like this :

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

export interface MethodRep {
    name: string;
}

export class BaseFileStructure {
    public methods: Methods;

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

Upvotes: 0

Related Questions