bluePearl bluePearl - 6 months ago 34
TypeScript Question

Interface class with nested classes in Typescript

I am trying to write up an interface class which also contains other classes but i am getting an error when i do so but not sure what is wrong:

Interface:

export interface Languages{
static English = class{
id: number,
section:number,
name: string
},
static Chinese = class{
id: number,
section: number,
name: string
}
}


Both
static
and
English
are showing errors stating:
[ts] Property or signature expected.
[ts] Cannot find name 'English'.

Answer Source

Interfaces is a contract, not an implementation. Your English and Chinese members are instances which is exactly what an interface cannot support. They are also static, which is also incorrect on an interface. You could refactor it like this:

export interface Languages{
   English: Language;
   Chinese: Language;
}

export interface Language {
    id: number;
    section:number;
    name: string;
}

A better design would be to use a dictionary or a list with a lookup especially if this is a non-fixed size list where languages may be added later. Something like this for example:

export interface Languages{
   getLanguageByCode(isoCode:string): Language;
   getLanguageById(id: number): Language;
   allLanguages: Language[];
}