Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript callback with generic function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading