Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有一种基于对象键在TypeScript上动态生成枚举的方法?_Typescript - Fatal编程技术网

是否有一种基于对象键在TypeScript上动态生成枚举的方法?

是否有一种基于对象键在TypeScript上动态生成枚举的方法?,typescript,Typescript,我正在定义一个对象,我想根据它的键动态生成enum,这样我就可以得到IDE建议,并且不会调用错误的键 const appRoutes = { Login, Auth, NotFound } enum AppRoutes = {[Key in keyof appRoutes]: [keyof appRoutes]} 无法从对象键生成实际枚举 您只需使用keyof typeof appRoutes即可获得所有键的并集,这将产生您想要的类型安全效果: type AppRoute

我正在定义一个对象,我想根据它的键动态生成enum,这样我就可以得到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;