Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript return the type of parameter

Tags:

Is there a way in TypeScript to indicate that the return is the type of a parameter, without explicitly declaring the type (e.g. in a generic parameter)? Sort of like indicating that it's a type identity function.

For example:

function foo(bar) {
    // ...do crazy stuff to bar...
    return bar;
}
var aString = foo('baz'); // aString is of string type
var aNumber = foo(6); // aNumber is of number type
like image 618
Josh Avatar asked Jul 27 '16 18:07

Josh


People also ask

Can you return a type in TypeScript?

We can return any type of value from the function or nothing at all from the function in TypeScript. Some of the return types is a string, number, object or any, etc. If we do not return the expected value from the function, then we will have an error and exception.

How do you find the return type of a function in TypeScript?

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction> . The ReturnType utility type constructs a type that consists of the return type of the provided function type.

What is return type in TypeScript?

The function's return type is string. Line function returns a string value to the caller. This is achieved by the return statement. The function greet() returns a string, which is stored in the variable msg.

Can you pass a type as a parameter TypeScript?

To type a function as a parameter, type the function's parameter list and its return value, e.g. doMath: (a: number, b: number) => number . If the function's definition becomes too busy, extract the function type into a type alias.


1 Answers

There is. They are called generics. In your case this how it would look like:

function foo<T>(bar: T): T {
  return bar;
}

var aString: string = foo('baz');
var aNumber: number = foo(6);

T will be the generic parameter that will take whichever type is passed in bar.

Also, you don't have to explicitly specify the generic parameter (string, number) as the compiler infers it from the actual value you're passing in each invocation. So the following would be valid and correctly inferred:

let aString = foo('bar'); // aString's type will be inferred as a string

You can read more about it on the official documentation: https://www.typescriptlang.org/docs/handbook/generics.html

like image 60
Alex Santos Avatar answered Oct 22 '22 09:10

Alex Santos