[英]how to use enum in react/typescript
關於枚舉的例子有三個,例如一,二,三。 我調用函數以不同的參數進行響應。 第二個結果使我感到困惑。 我認為TS會像第一個示例一樣檢查類型並告訴我問題。(類型為“ test”的參數不能分配給類型為“ Response”的參數。ts)數字9沒有在Response中退出但不會拋出錯誤! 如何確保型號安全? (我的意思是,響應參數必須是枚舉中包含的數字,而不是9或其他)
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);
響應參數必須為數字,該數字應包含在枚舉Response中,TS會告訴我如何修復它。
在這種情況下,我認為正確的是定義這種情況的類型。
// 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;
從而確保您的應用是類型安全的。
我找到了感覺很好的答案。
實際上,任何僅具有數字值的枚舉實際上只是數字的別名-您可以分配不在枚舉中的值。 原因是枚舉經常被用作位域,因此它必須能夠表示諸如Flags.A |之類的東西。 標志B | 旗
如果要使用更多類型安全的枚舉,可以嘗試使用字符串值而不是數字。
您在另一個問題中要求使用enum
的替代方法。 您可以使用枚舉來構造答案,而在原始問題中不允許使用像9
這樣的整數。
例如,使用:
const enum MyResponse {
No = "No",
Yes = "Yes"
}
function respond(message: MyResponse): void {
console.log(message);
}
將允許編寫:
respond(MyResponse.No);
不允許傳遞數字:
respond(9);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.