4
votes

Consider the following enum:

enum Numbers {
  ONE=1,
  TWO=2
}

The following interface definition throws compile-time errors.

interface Config {
  [n in Numbers]: string;
}
  • A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
  • A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
  • Cannot find name 'n'.

But if I use a type alias:

type Config = {
  [n in Numbers]: string;
}

Or move the mapped type deeper in the definition:

interface Config {
  a: {
    [n in Numbers]: string;
  };
}

It compiles just fine.

So, why a top level property of an interface can not be a mapped type?

PS: On typescript playground using v4.2.3.

1

1 Answers

4
votes

TypeScript does not currently support doing this with interfaces—I’m not sure if there’s a reason for why it doesn’t though besides “it hasn’t been implemented”.

Thankfully, this appears to be on the roadmap for TS4.4 via this PR: https://github.com/microsoft/TypeScript/pull/26797

Edit: As explained in the comments below the above PR doesn’t fully cover the behavior desired in the original question.