TypeScript return the type of parameter

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)