29

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

1 Answer 1

38

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

1
  • 4
    Oh, cool, I never thought to try it without specifying the type on the call...oops. Thanks.
    – Josh
    Jul 27, 2016 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.