9

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

5

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the ansver. Is it possible to create an object with properties from interface keys?
Yes, added you a sample
Thank you, could you please advise, it is possible to define such object automaticaly in some function?
keyof Enum works perfectly

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.