![](/img/trans.png)
[英]Typescript function arguments based on types with enums as keys
[英]Is there a way to dynamically generate enums on TypeScript based on Object Keys?
我正在定義一個對象,我想根據它的鍵動態生成枚舉,所以我得到了 IDE 建議並且不要調用錯誤的鍵。
const appRoutes = {
Login,
Auth,
NotFound
}
enum AppRoutes = {[Key in keyof appRoutes]: [keyof appRoutes]}
您不能從對象鍵構建實際的枚舉。
您可以使用keyof typeof appRoutes
獲得所有鍵的聯合,這將具有您想要的類型安全效果:
type AppRoutes = keyof typeof appRoutes
let ok: AppRoutes = "Auth";
let err: AppRoutes = "Authh";
枚舉不僅是一種類型,它還是一個包含枚舉的鍵和值的運行時對象。 Typescript 不提供從字符串聯合自動創建此類對象的方法。 然而,我們可以創建一個類型來確保對象的鍵和聯合的成員保持同步,如果它們不同步,我們會得到編譯器錯誤:
type AppRoutes = keyof typeof appRoutes
const AppRoutes: { [P in AppRoutes]: P } = {
Auth : "Auth",
Login: "Login",
NotFound: "NotFound" // error if we forgot one
// NotFound2: "NotFound2" // err
}
let ok: AppRoutes = AppRoutes.Auth;
我使用此解決方法將鍵轉換為 const key -> key 對象:
const { Login, Auth, NotFound } = {} as any
const appRoutes = {
Login,
Auth,
NotFound
}
const AppRoutes = (() => ({
...Object.keys(appRoutes)
.filter(k => isNaN(Number(k)))
.reduce((acc, cur) => ({
...acc,
[cur]: cur,
}), {}),
} as {
[k in keyof typeof appRoutes]: k
}))()
console.info(AppRoutes)
// AppRoutes: {
// Login: "Login";
// Auth: "Auth";
// NotFound: "NotFound";
// }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.