Reputation: 19
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)
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);
The respond params have to be number which include in the enum Response and TS tell me how to fix it.
Upvotes: 0
Views: 4659
Reputation: 140833
You asked for an alternative using enum
in the other question. You could use enum for conscribing the answer and not allowing integer like the 9
in your original question.
For example, using:
const enum MyResponse {
No = "No",
Yes = "Yes"
}
function respond(message: MyResponse): void {
console.log(message);
}
Would allow writing:
respond(MyResponse.No);
An disallow passing a number:
respond(9);
Upvotes: 0
Reputation: 19
I find the answer what i feel good.
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.
https://github.com/microsoft/TypeScript/issues/32227
Upvotes: 1
Reputation: 10307
In this case, what I consider to be correct is defining a type for this situation.
// you can export these to use around app
export const YES = 'YES';
export const NO = 'NO';
type TypeSafeResponse = 'YES' | 'NO';
// this one errors like it should
const response: TypeSafeResponse = 3;
// this one errors like it should
const response2: TypeSafeResponse = 'test';
// this one is allowed like it should
const response3: TypeSafeResponse = YES;
Thus ensuring your app is typesafe.
Upvotes: 0