打字稿枚举动态访问错误

Typescript Enum dynamically accessing error

我想像 Routes[] 一样访问枚举,但由于某些原因打字稿返回错误

Property 'Help' does not exist on type 'String'.

enum Routes {
    Help = 'help',
}

type test = Routes['Help'];
type test2 = Routes.Help;

基本上我想用下面的前缀扩展路由名称

type TransformRoute<Type extends Record<string, string>, Prefix extends keyof typeof Routes> = {
    [Property in keyof Type as `${string & Prefix}${string & Property}`]: `${string & Routes[Prefix]}${string &
        Type[Property]}`;
};

但是这里我得到错误

Type 'Prefix' cannot be used to index type 'Routes'.

有人对此主题有任何意见吗?

枚举基本上是对象,因此在从中创建类型时必须这样对待它们。你可以这样做:

// Notice the keyof typeof in ${string & keyof typeof Routes[Prefix]}
type TransformRoute<Type extends Record<string, string>, Prefix extends keyof typeof Routes> = {
    [Property in keyof Type as `${string & Prefix}${string & Property}`]: `${string & keyof typeof Routes[Prefix]}${string &
        Type[Property]}`;
};

你可以玩它here