0

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.

1 Answer 1

2

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'.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.