Home > front end >  typescript callback with generic function
typescript callback with generic function

Time:05-21

I have the following code:

type callbackType = <T>(d: T) => void;

const callbackTest = <T>(val: T, callback: callbackType) => {
    callback(val);
};

callbackTest("Hey", isAString => isAString)

Here I would expect Typescript to deduce that isAString has the type string, which it doesn't.

if i inline the callbackType like so:

const callbackTest = <T>(val: T, callback: (d: T) => void) => {
    callback(val);
};

callbackTest("Hey", isAString => isAString)

Typescript can deduce that isAString has the type string.

I Tryed adding a <T> behind callbackType (callback: callbackType<T>), but this doesn't seem to be valid Typescript and gives the following error: Type 'callbackType' is not generic.

In my real code callbackType is a more complex function that I use multiple times, therefore inlining it wouldn't be ideal.

Any ideas how I could help Typescript figure out the type of isAString?

CodePudding user response:

Move the generic to the type from the function:

type callbackType<T> = (d: T) => void;

Then you can pass T to the type like you originally tried:

const callbackTest = <T>(val: T, callback: callbackType<T>) => {
    callback(val);
};

callbackTest("Hey", isAString => isAString);
  • Related