有没有办法根据对象键在 TypeScript 上动态生成枚举?

Cai*_*rêa 12 typescript

我正在定义一个对象,我想根据它的键动态生成枚举,所以我得到 IDE 建议并且不要调用错误的键。

const appRoutes = {
   Login,
   Auth,
   NotFound
} 

enum AppRoutes = {[Key in keyof appRoutes]: [keyof appRoutes]}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 19

您不能从对象键构建实际的枚举。

您可以使用 just 获得所有键的联合,keyof typeof appRoutes这将具有您想要的类型安全效果:

type AppRoutes = keyof typeof appRoutes

let ok: AppRoutes = "Auth";
let err: AppRoutes = "Authh";
Run Code Online (Sandbox Code Playgroud)

枚举不仅仅是一种类型,它还是一个运行时对象,包含枚举的键和值。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;
Run Code Online (Sandbox Code Playgroud)