#Making a type that allows all possible values within an object regardless of the nesting

16 messages · Page 1 of 1 (latest)

reef dune
#

I've got the following object

const api = {
  auth: {
    register: '/admin/auth/register',
    login: '/admin/auth/login',
    logout: '/admin/auth/logout',
  },
  user: {
    details: '/admin/user/details',
    password: '/admin/user/password',
  },
  quiz: {
    create: '/admin/quiz',
    trash: '/admin/quiz/trash',
    trashEmpty: '/admin/quiz/trash/empty',
  },
  question: '/admin/quiz/question'
} as const;

What I would like is a type ApiType that allows me to access all values of this object - e.g api.auth.login, api.question, etc
Is this possible?

neon quarryBOT
#
evan.trimboli#0

Preview:ts const api = { auth: { register: "/admin/auth/register", login: "/admin/auth/login", logout: "/admin/auth/logout", }, user: { details: "/admin/user/details", password: "/admin/user/password", }, quiz: { create: "/admin/quiz", ...

reef dune
#

@pseudo needle you misunderstand

#

const myFn = (path: ApiType) => ...

#

myFn(api.auth.login) is allowed, but myFn('random string') is not allowed

reef dune
pseudo needle
#

So essentially you just want a union of all those strings?

reef dune
#

yes

reef dune
pseudo needle
#

Maybe something like this

neon quarryBOT
#
evan.trimboli#0

Preview:ts const api = { auth: { register: "/admin/auth/register", login: "/admin/auth/login", logout: "/admin/auth/logout", }, user: { details: "/admin/user/details", password: "/admin/user/password", }, quiz: { create: "/admin/quiz", ...

reef dune
#

how about this

#
type ApiRoute<T extends object> = { [Key in keyof T]: T[Key] extends object ? ApiRoute<T[Key]> : T[Key] } [keyof T];
reef dune
#

!resolved

#

this works nicely

#

Thank you