Given the following ROUTES
:
const ROUTES = [
{ name: "Login", path: "/login", id: "login" },
{ name: "Registration", path: "/registration", id: "registration" },
{ name: "Settings", path: "/settings", id: "settings" },
] as const;
How can I create a type (SomeType
) for which:
- every
id
is used as a key - every
path
is used as a value - all keys (
id
) are matched 1-to-1 with their value (path
) given theROUTES
configuration
For example:
# correct
const correctIdToPaths: SomeType = {
login: "/login",
registration: "/registration",
settings: "/settings",
} as const
# wrong
const duplicatedValues: SomeType = {
login: "/registration", # error, id "login" does not match path "/registration"
registration: "/registration",
settings: "/settings",
} as const
# wrong
const missingKey: SomeType = {
login: "/login",
registration: "/registration",
} as const # error: "settings" is missing
CodePudding user response:
You can use typeof ROUTES[number]
to get a union of the Route
s in the array, and create a mapped type where you remap the key to the id:
type SomeType = {[Route in typeof ROUTES[number] as Route['id']]: Route['path']}
// type SomeType = {login: "/login", registration: "/registration", settings: "/settings"}