0

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

1 Answer 1

1

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"'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution, it works fine. Is it possible to define the array of items outside the function? like in my example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.