我正在定义一个对象,并且想根据其键动态生成枚举,因此我得到了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;

关于typescript - 有没有一种方法可以基于对象键在TypeScript中动态生成枚举?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54058699/

10-11 11:27