将字符串数组转换为字符串文字联合类型

Convert an array of strings into string literal union type

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

示例:

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 函数以便能够从传递的路由数组创建字符串联合类型?

Playground

这可能是您要查找的内容:

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"'