'Why any number value can be used in interface member declared with enum literal type? [duplicate]
I have the following typescript enum:
enum Status {
READY = 0,
FAILED = 1
}
and the following interface:
interface ReadyItem {
id: number;
status: Status.READY;
}
Why am I able to redeclare the value of status in the following case?
const readyItem: ReadyItem = {
id: 1,
status: 58 // no error here
}
If I change my enum number values to string values, it works as intended:
enum Status {
READY = "ready",
FAILED = "failed"
}
interface ReadyItem {
id: number;
status: Status.READY;
}
const readyItem = {
id: 1,
status: 'other' // error: Type 'other' is not assignable to type 'Status.READY'.
}
Can someone tell me how I can have this behavior with number values?
Solution 1:[1]
I think it should be
...
interface ReadyItem {
id: number;
status: Status;
}
...
Now you're constraining status prop to accept only one value from enum
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sergei Klinov |
