将字符串数组转换为字符串文字并集类型



我试图在函数内将字符串数组从值转换为字符串并集类型。但无法实现。

示例:

const makeGet = (paths: string[]) => (path: typeof paths[number]) => paths.includes(path)
const makeGet2 =
<T extends string>(paths: string[]) =>
(path: T) =>
paths.includes(path)
const routes = ['users', 'todos']
const readonlyRoutes = ['users', 'todos'] as const
const get = makeGet(routes)
const get2 = makeGet2<typeof readonlyRoutes[number]>(routes)
get('users') // no ts support
get2('users') // yes ts support

我应该如何重构我的makeGet函数,以便能够从传递的路由数组中创建字符串联合类型?

游乐场

这可能是您想要的:

const makeGet =
<T extends string>(paths: ReadonlyArray<T>) =>
(path: T) =>
paths.includes(path);
const routes = ["users", "todos"] as const;
const get = makeGet(routes);
get("users");
get("user"); // Argument of type '"user"' is not assignable to parameter of type '"users" | "todos"'

最新更新