1

i'm curious that usage of enum with keyof keyword.
here is the sample code without enum.

const map = new Map<string, string>();

interface ShopStoreProps {
    google: string;
    apple: string,
    galaxy: string
}

const setValue = <T extends keyof ShopStoreProps>(shopProps: T, value: string) => {
    return map.set(shopProps, value);
}

setValue('google', 'test1'); // ok
setValue('appleee', 'test2'); // error

but I want to use only enum not the upper interface like this.
of course I know that the below setValue function is wrong grammatically.
thank you for reading this question. :)

const map = new Map<string, string>();

enum ShopStoreEnum {
    GOOGLE = 'google',
    APPLE = 'apple',
    GALAXY = 'galaxy',
}

const setValue = <T extends keyof ShopStoreEnum>(shopProps: T, value: string) => {
    return map.set(shopProps.name, value);
}

setValue(ShopStoreEnum.GOOGLE, 'test1'); // to be
1
  • Does setValue have to be generic on type shopProps ? Commented Jun 21, 2021 at 4:32

1 Answer 1

2

Instead of extends keyof simply use extends.

const setValue = <T extends ShopStoreEnum>(shopProps: T, value: string) => {
    return map.set(shopProps, value);
}

One might ask, why make it generic at all? You would achieve the same result with this:

const setValue = (shopProps: ShopStoreEnum, value: string) => {
    return map.set(shopProps, value);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I guess I thought it was too hard. thank you

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.