Asur
Asur

Reputation: 2057

Typescript conditional types based upon a function type

Is it possible in Typescript to write a conditional type based upon a function type?

We can implement conditional types based up on an object interface but was wondering if we can do the same with respect to a function type.

Something like below:

type func<T> = (val: any) => T
type Optional<T> = (val: any) => T | undefined

type FilterOptional<T> = T extends Optional<any> ? undefined : T

type a = FilterOptional<(val: any) => number>
// a is undefined but need it to be (val: any) => number

Upvotes: 0

Views: 120

Answers (2)

Alvin Leung
Alvin Leung

Reputation: 798

If your intention is to return undefined if the return type contains undefined, then you may try this:

type FilterOptional<T extends (...args: any) => any> = undefined extends ReturnType<T> ? undefined : T

type a = FilterOptional<(val: any) => number> // (val: any) => number
type b = FilterOptional<(val: any) => number | undefined> // undefined

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187034

You sure can.

In fact, your code works without modification. I'll just add some examples:

type func<T> = (val: unknown) => T

type foo<T> = T extends func<any> ? T : undefined // some other types

// Take positive conditional branch
type A = foo<() => void> // () => void
type B = foo<(val: number) => void> // (val: number) => void

// Take negative conditional branch
type C = foo<(val: number, secondArg: string) => void> // undefined
type D = foo<number> // undefined

Playground

Upvotes: 0

Related Questions