0

There is a list of keys can be enum, array anything like keys = ["x","y","z"]

Need to implement an interface which can have key from this array

something like:

interface Points {
   [index: keys]: string
}

But this doesn't work as index can only be string or number.

What is better way to achieve this?

SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68
Sahil
  • 67
  • 8

1 Answers1

1

If they keys are known at compile-time you could do something like this:

type Keys = 'x' | 'y' | 'z';

type Points = {
  [key in Keys]: string;
}

This will require a Point record to have all the keys. You can make them optional with [key in Keys]?: string.

If the keys are not known at compile-time, you can't really type check it with Typescript can you ;)

Phillip
  • 6,033
  • 3
  • 24
  • 34