6

I have an interface:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}

Is it possible to define Enum which will represent keys from the interface?

I would like to get result like this:

enum SomethingKeys {
   red = "red",
   blue= "blue",
   green= "green",
}

ps: I'm newbie in ts, sorry if the question isn't correct.

1 Answer 1

4

You can do other way around by creating an object with keys of enum:

enum SomethingKeys {
   red = "red",
   blue= "blue",
   green= "green",
}
type ISomething= Record<SomethingKeys, string>
const a: ISomething = {
    [SomethingKeys.blue]: 'blue',
    [SomethingKeys.red]: 'red',
    [SomethingKeys.green]: 'green',
}

But I think what you really need is not enum but union type of keys, what you define by keyof. Consider:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}
type Keys = keyof ISomething; // "red" | "blue" | "green"

And as you declare yourself as newbie, string literal unions are ok to be used. You don't need enums.

When you have Keys you can use them to create other types also

// new object with keys of the original one
type OtherTypeWithTheSameKeys = Record<Keys, number> // type with keys of type Keys
const a: OtherTypeWithTheSameKeys = {
  blue: 1,
  green: 2,
  red: 3
}
3
  • Thanks for the ansver. Is it possible to create an object with properties from interface keys? Jan 23, 2020 at 16:20
  • 1
    Yes, added you a sample Jan 23, 2020 at 16:24
  • Thank you, could you please advise, it is possible to define such object automaticaly in some function? Jan 25, 2020 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.