1

I am struggling to create an interface that uses values from an Enum.

enum TestEnum {
  'VAL1' = 'TEST1',
  'VAL2' = 'TEST2'
}

interface IMyInterface {
  [TestEnum[key in TestEnum]]: {
    // some code
  }
}

const objToType: IMyInterface = {
  TEST1: { / ** \ }
  TEST2: { / ** \ }
}

It throws an error

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.

What's the problem here?

1 Answer 1

1

I think the confusing bit is that [key in TestEnum] returns the "values" of the enum rather than the "keys" (if you want to iterate the keys you'd use [key in keyof TestEnum]).

This is easy to do using a type declaration rather than an interface declaration:

enum TestEnum {
  'VAL1' = 'TEST1',
  'VAL2' = 'TEST2'
}

type IMyInterface = {
  [key in TestEnum]: { /* */ }
}

const objToType: IMyInterface = {
  TEST1: { },
  TEST2: { }
}

Playground link

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.