javascripttypescriptenums

A mapped type may not declare properties or methods - TypeScript


I have an interface, which should have keys that are in specific enum key type, but when I declare the type it gives this error:

A mapped type may not declare properties or methods.

Here is the code:

enum myEnum {
  propOne = 'propOne',
  propTwo = 'propTwo'
}

export interface myInterface {
  [key in myEnum]: anotherInterface;
}

I tried to specify the type also like this, but it didn't work and gave me syntax error:

export interface myInterface {
  [key in keyof typeof myEnum]: anotherInterface;
}

I also tried to use a normal object instead of an enum, but it gave the same error.


Solution

  • You need to use Mapped type, not interface:

    export type MyInterface = {
      [key in myEnum]: AnotherInterface;
    }