4

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

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.