0

I have a enum as below.

export enum Hotkey {
    MARK_IN = 'markIn',
    MARK_OUT = 'markOut',
    GO_TO_MARK_IN = 'goToMarkIn',
    GO_TO_MARK_OUT = 'goToMarkOut'
}

Now i want to create a type for a json object that should allow only the keys present in enum but not some random key during development.

type hotkey = keyof typeof Hotkey;

type clone = {[key:hotkey]: string}

const finalObject: clone = {
    MARK_IN : 'markIn'
};

i created the type as above but that is erroring out when i create the type "clone"

Error: An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)

2
  • There is no such thing as a JSON-'object' Commented Dec 6, 2022 at 15:11
  • @KooiInc I know it's popular to keep reposting that, but it never sits right with me: a JSON object is an object that can be serialized to/from a JSON string. That definition is fairly intuitive and matches the way people use the term "JSON object" in the common parlance. Commented Dec 6, 2022 at 16:16

1 Answer 1

1

You can create a type using an enum for the key this way:

export enum Hotkeys {
  MARK_IN = 'markIn',
  MARK_OUT = 'markOut',
  GO_TO_MARK_IN = 'goToMarkIn',
  GO_TO_MARK_OUT = 'goToMarkOut'
};

type IHotkey = `${ Hotkeys }`;

type IClone = {
  [key in IHotkey]?: string
};

If you want to use the enum member as the key you can also do:

const yourObject: IClone = {
  [Hotkeys.MARK_IN] = 'your-value'
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer Brandon. This was accepting the values in enum as key in my object. const finalObject: Iclone = { markIn : 'something' }; But i am expecting the other way round. like const finalObject: Iclone = { MARK_IN : 'markIn' };
@Niranjan I've updated the answer with an example

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.