Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ensure Exhaustiveness and Correctness of Object based on Const Array of Objects

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading