Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if type is undefined in Typescript Conditional Types?

I currently have this type:

type ReturnType<T, E> = [T, E]

I 'm trying to make this type "smarter" by these rules:

  • If T is undefined, then the type would be [undefined, E]
  • If E is undefined, then the type would be [T]
  • T and E can't both be undefined

I'm trying to apply these rules using Typescript's Conditional Types.
Is this even possible to implement?

This is what I got so far:

type ReturnType<T, E> = 
    T extends undefined 
    ? E extends undefined ? never : [undefined, E]
    : E extends undefined ? [T] : never
like image 866
Two Horses Avatar asked Oct 31 '25 05:10

Two Horses


1 Answers

What you seem to be missing is that you can do tests for both T and E at the same time with:

[T, E] extends [TypeA, TypeB] ? ... : ...

Putting that to use you can do:

type MyReturnType<T, E> = 
    [T, E] extends [undefined, undefined] ? never
    : T extends undefined ? [undefined, E]
    : E extends undefined ? [T]
    : [T, E]

type A = MyReturnType<undefined, undefined> // never
type B = MyReturnType<string, undefined> // [string]
type C = MyReturnType<undefined, number> // [undefined, number]
type D = MyReturnType<boolean, string> // [boolean, string]

Playground

like image 56
Alex Wayne Avatar answered Nov 01 '25 21:11

Alex Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!