Abid Rahim
Abid Rahim

Reputation: 13

TypeScript: How to set function return value type based on function argument type

Let's say there's a function with parameters paramA (string) and paramB (object)

const dummyFunction = (paramA: string, paramB: { defaultValue: any }) => {

 }

I want to remove the any from the defaultValue key in paramB object (It can be of any type)

Requirement is to give type to function return value based on defaultValue key in paramB. How to achieve it?

Upvotes: 0

Views: 275

Answers (1)

Marek Urbanowicz
Marek Urbanowicz

Reputation: 13634

The thing which you need is generics.

Not sure if I got your intention right, but you would need to go with something like this:

const dummyFunction = <T>(paramA: string, paramB: { defaultValue: T }): T => {

}

It will then infer the return type from the type of the defaultValue

Upvotes: 1

Related Questions