Home > front end >  How to get type from the return of a function?
How to get type from the return of a function?

Time:10-29

I'm trying to make a pseudo pipeline in typscript. The idea is that I would have a function that returns me an object. Then I would pass this object to other functions that can process this object.

The function signature would be something like this:

type FirstFunc<T> = () => T;
type Pipeline<T> = ((obj: T) => T)[]

const objPipeLine<T> = (firstFunc: FirstFunc<T>, pipeline: Pipeline<T>): T

But I don't want to provide the generic to this function. I want it to know what type of object the first function would return and use it as my T generic. Something like an implicit typing, the functions in the Pipeline should only accept parameters matching the kind of object my first function returns.

CodePudding user response:

FIrst of all this syntax is wrong: const objPipeLine<T>.

If you want to infer function argument, you should do const objPipeLine=<T>()=>{}.

Just put generic right after equal sign.

COnsider this example:

type FirstFunc<T> = () => T;
type Pipeline<T> = ((obj: T) => T)[]

const objPipeLine = <Return,>(firstFunc: FirstFunc<Return>, pipeline: Pipeline<Return>) => {}

const result = objPipeLine(
    () => ({ age: 42 }),
    [(obj) => obj]
)

Playground

I have created Return generic and let TS to infer it. If you hover your mouse on obj in [(obj) => obj] you will see that it is infered as {age: number}.

If you are interested in typing pipeline function you can check my article, this answer and this answer

CodePudding user response:

That's what typescript is made for, to specify them types, to assign a type to the return type we use ReturnType

type some=ReturnType<FirstFunc<T>>
  • Related