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

Conditional type depending on payload function in TS

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

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

>Solution :

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>
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