How can I return the same type as a I pass into a function in TypeScript?

Is there a way to make a function which returns whatever the type of one of its arguments is in TypeScript?

The answer is yes! There’s only one way, and that’s to use TypeScript generics.

Let’s look at an example, here’s a normal function that accepts a number type.


function returnWhatIPassInWithTypeScript(val: number) {
    return val;
}

// Argument of type 'string' is not assignable to parameter of type 'number'.
returnWhatIPassInWithTypeScript('3')

// Argument of type 'boolean' is not assignable to parameter of type 'number'.
returnWhatIPassInWithTypeScript(true)

Some developers first instinct is to use the keyword any, but that’s incorrect. The right way to solve this issue is to use generics in TypeScript.

Let’s look at an example of how to use generics in TypeScript:


function returnWhatIPassInWithTypeScript<T>(val: T) {
    return val;
}

// '3'
returnWhatIPassInWithTypeScript('3')

// true
returnWhatIPassInWithTypeScript(true)

You want to let TypeScript know that <T> the value can be anything and the result is going to be whatever you pass in.

Here’s an example of a function that is assigned to a variable using a generic.


const returnWhatIPassInWithTypeScript = <T>(val: T) => {
    return val;
}

I like to tweet about TypeScript and post helpful code snippets. Follow me there if you would like some too!