typescript - 為什麼任何數字值都可以用在宣告為 enum 字面量類型的介面成員中?
我有以下 TypeScript 列舉型別:
enum Status {
READY = 0,
FAILED = 1
}
以及以下介面:
interface ReadyItem {
id: number;
status: Status.READY;
}
為什麼在以下情況下我能夠重新宣告 status 的值?
const readyItem: ReadyItem = {
id: 1,
status: 58 // no error here
}
如果我將我的枚舉數值改成字串值,它就能如預期般運作:
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'.
}
有人能告訴我如何讓數值具有這種行為嗎?
遊樂場連結
答案#1
我認為它應該是
...
interface ReadyItem {
id: number;
status: Status;
}
...
現在你正在將 status 屬性限制為只能接受枚舉中的一個值
