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

Enum question in react/typescript #32227

Closed
cyzeng-Luca opened this issue Jul 3, 2019 · 2 comments
Closed

Enum question in react/typescript #32227

cyzeng-Luca opened this issue Jul 3, 2019 · 2 comments

Comments

@cyzeng-Luca
Copy link

TypeScript Version: ^3.5.1

Question :

There are three examples about enums like one, two, three. And I call function respond with different param. The second result puzzles me. I think TS will check type like the first example and tell me the problem.(Argument of type '"test"' is not assignable to parameter of type 'Response'.ts)The number 9 is not exit in Response but it not throw errors! How to ensure the type safety ? (I mean the respond params have to be number which include in the enum Response not 9 or others)
Code

const enum Response {
  No = 0,
  Yes = 1
}

function respond(message: Response): void {
  console.log(message);
}

// one
respond("test");
// two
respond(9);
// three
respond(Response.Yes);

Expected behavior:
The respond params have to be number which include in the enum Response and TS tell me how to fix it.

Actual behavior:
The example two doesn't throw error;

any: I just ask for stack overflow, but the effect is not good;
link: https://stackoverflow.com/questions/56849551/how-to-use-enum-in-react-typescript?answertab=active#tab-top

@fatcerberus
Copy link

fatcerberus commented Jul 3, 2019

Any enum with only numeric values is mostly just an alias for number in practice--you can assign values that aren't in the enum. The reason for this is that enums are often used as bitfields, so it needs to be able to represent stuff like e.g. Flags.A | Flags.B | Flags.C.

If you want a more typesafe enum, you can try using string values instead of numbers.

@cyzeng-Luca
Copy link
Author

Thanks, it works on me.

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

No branches or pull requests

2 participants