Home > Back-end >  Conditional type depending on payload function in TS
Conditional type depending on payload function in TS

Time:07-21

Is it possible to determine a type depending on a payload function ?

Example:

export const myFunction = (
  findAll: boolean
) => {
  const finders: { key: findAll extends true ? VueWrapper<T>[] : VueWrapper<T> } = {}
})

Here I want to change the finders type to an Array if findAll is at true

CodePudding user response:

It is possible with Conditional Types.

type FindOrFindAllResult<TElement, TFindAll extends boolean>
  = TFindAll extends true
    ? TElement[]
    : TElement

const myFunction = <T, TFindAll extends boolean = boolean>(
  findAll: TFindAll
):FindOrFindAllResult<VueWrapper<T>, TFindAll> => {
  if (findAll) {
    return [] // replace with your function returning array
  }
  else {
    return null // replace with your function returning one element
  }
}


const arrayResult = myFunction(true) // arrayResult is of type VueWrapper<T>[]
const elementResult  = myFunction(false) // elementResult is of type VueWrapper<T>
  • Related