Typescript: pick union of function type

Viewed 30
type UnionThing<T> = T | (value:T)=>T

I have union type like this : one generic primitive value and one function type

type FnThing<T> = ~~~~~ // expect it to be (value:T)=>T

Now I want to pick function type only but don't know how to. Utility Type Pickis for key value and I don't have key in this union type. How can I achieve this?

1 Answers

The problem here is that your expected type is not valid TypeScript.

This

type FnThing = (value: T) => T

would not compile since T is not declared anywhere. So we will have to either make FnThing generic over T or subsitute a type for T.

type FnThing<T> = Extract<UnionThing<T>, (args: any) => any>

type WithoutGeneric = FnThing<number>
// type WithoutGeneric = (value: number) => number

or

type FnThing2 = Extract<UnionThing<number>, (args: any) => any>
// type FnThing2 = (value: number) => number

Playground

Related