typescripttypestypescript-typingstypescript-genericsgeneric-type-parameters

Convert an array of strings into string literal union type


I'm trying to convert an array of strings from the value to the string union type inside a function. But can't achieve it.

Example:

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

How should I refactor my makeGet function to be able to create a string union type from the passed routes array?

Playground


Solution

  • This could be what you are looking for:

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