Home > Software design >  Ensure Exhaustiveness and Correctness of Object based on Const Array of Objects
Ensure Exhaustiveness and Correctness of Object based on Const Array of Objects

Time:02-03

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:

  1. every id is used as a key
  2. every path is used as a value
  3. all keys (id) are matched 1-to-1 with their value (path) given the ROUTES 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 Routes 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"}

TypeScript playground

  • Related