Home > Back-end >  Is it possible to have dynamic type based on another type in Typescript?
Is it possible to have dynamic type based on another type in Typescript?

Time:11-24

I have a type like this:

type PageList = 'login' | 'register' | 'dashboard'

For every page, it has a different object to send, for example:

const PageParam = [
  { 
    login: {
     isAuthenticated: true
    }
  },
  { 
    register: {
     isRegistered: false
    },
  },
    
]

And I need to use it in function like this:

function moveTo(pageName: PageList, bodyParam: ???) {
  /* Some Logic */
}

// I want it goes this way
// JUST EXAMPLE!!
if (pageName === 'login') typeof bodyParam = { isAuthenticated: boolean }
if (pageName === 'register') typeof bodyParam = { isRegistered: boolean }

I need those bodyParam to have type following the pageName so I can send the right param without checking the type file again.

Is there any possible way to achieve this?

CodePudding user response:

Yes you can set up the equivalent of a dictionary of types:

type PageParam = {
    login: {
        isAuthenticated: boolean
    },
    register: {
        isRegistered: boolean
    },
    dashboard: {}
}

function moveTo<T extends PageList>(pageName: T, bodyParam: PageParam[T]) {
  /* Some Logic */
}

moveTo('login', {
    isAuthenticated: true // Okay
})

moveTo('register', {
    isAuthenticated: true // Error: Argument of type '{ isAuthenticated: boolean; }' is not assignable to parameter of type '{ isRegistered: boolean; }'
})

Playground Link

  • Related