I am working with a specific type of interface called Route that consists of name and path properties.
interface Route {
name: string,
path: string
}
const routes = [
{
name: "first",
path: "/first"
},
{
name: "second",
path: "/second"
}
] as const
My goal is to develop a function that can retrieve the path for a given route based on its name.
const to = <Routes extends ReadonlyArray<Route>, CurrentRoute extends Routes[number]>(routes: Routes, name: CurrentRoute["name"]): CurrentRoute["path"] => {
// Implementation details are not important here
return "" as CurrentRoute["path"]
}
const path = to(routes, "first")
// Currently returns a union instead of a string
What I need is for this function to accurately return a single string inferred from the corresponding object's name:
"/first"
should be returned by TypeScript when calling the function with"first"
"/second"
should be returned by TypeScript when calling the function with"second"
- ...
The actual implementation of the function is trivial; what I am seeking is a solution within TypeScript's type system.