Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use keyof typeof for enums #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

qix
Copy link

@qix qix commented May 29, 2018

Enum types in TypeScript are not actually just the enum values. The types land up being restricted to string internally rather than the actual values. This makes the types a little stricter.

@dangcuuson
Copy link
Owner

Hi qix,

Could you explain more about your case?

From my understanding, I think you mean that TypeScript treats enum as equivalent to string.

However, in my projects I have to use the enum values to assign to a variable with corresponding enum type.

E.g:

enum Color {
    RED = 'RED',
    GREEN = 'GREEN',
    BLUE = 'BLUE'
}

const color1: Color = Color.RED; // this one is ok
const color2: Color = 'RED'; // TypeScript complains in this case

however, compare enum value with string is ok

switch (color1) {
    case 'RED': // fine
    case Color.R:  // fine
    case 'YELLOW': { // TypeScript complains in this case
        break;
    }
    
    default: {
        break;
    }
}

I'm not sure whether if it's due to some different in tsconfig.json file or not.

The reason why I need to clarify this is because there is a catch here: keyof typeof enum refers to the keys of that enum, not the actual value. Therefore, it only works when the enum's keys are the same as its values. E.g:

// note that the enum keys were changed to R/G/B instead of RED/GREEN/BLUE
enum Color {
    R = 'RED',
    G = 'GREEN',
    B = 'BLUE'
}

const color1: Color = Color.R;
console.log(color1); // RED

const color2: keyof typeof Color = 'R'; // assign 'RED' will make TypeScript complains
console.log(color2); // R

This catch is not a problem in this library since the enum keys and values are always the same. However, it could lead to some troubles in the future :) Maybe we could wrap your implementation in a config option?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants