Reputation: 2534
What I'm trying to achieve is something like this:
function genericFunc<T>(arg: T): T {
return arg;
}
//this line won't work, but it's the essence of what I need
var stringFunc = genericFunc<string>;
stringFunc('myStr')
Is it possible to create an instance of a generic function with a specified type?
The only way I know is to create an interface -
interface GenericFnInterface<T> {
(arg: T): T;
}
let stringFunc : GenericFnInterface<string> = genericFunc;
but I would like to avoid creating too many interfaces. Is there a shorter way to achieve the same
_
UPD Another way I found is
var stringFunc: <T extends string>(arg:T) => T = genericFun;
but it's still not exactly perfect, as it creates a lot of clutter with more complex types.
Upvotes: 0
Views: 78
Reputation: 174937
You can cast (either implicitly or explicitly):
declare function identity<T>(arg: T): T; // implementation irrelevant
const x: (arg: string) => string = identity; // implicit cast
x('hello'); // ok
x(42); // error
or
declare function identity<T>(arg: T): T;
const x = identity as (arg: string) => string; // explicit cast
x('hello'); // ok
x(42); // error
The former is recommended, because it would catch you if you make a mistake in the cast:
const x: (arg: string) => number = identity; // implicit cast
~ --> Error: Type 'string' is not assignable to type 'number'.
Upvotes: 2