0

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?

0

1 Answer 1

2

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);
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.