有没有一种方法可以基于对象键在TypeScript上动态生成枚举?

时间:2019-01-06 04:44:59

标签: typescript

我正在定义一个对象,并且想基于其键来动态生成枚举,所以我得到了IDE建议并且不会调用错误的键。

const appRoutes = {
   Login,
   Auth,
   NotFound
} 

enum AppRoutes = {[Key in keyof appRoutes]: [keyof appRoutes]}

1 个答案:

答案 0 :(得分:2)

您无法通过对象键构建实际的枚举。

仅使用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;