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

Why do Typescript arrow function generics not work as same as named function generics

In TS Playground when I declare arrow function like this:

    const singleArgumentSpy: <T>() => {
        fn: (arg: T) => void, 
        receivedArgument: () => T
    } = () => {
        let receivedArgument: T; // error: Cannot find name 'T'.ts(2304)
        return {
            fn: (arg) => (receivedArgument = arg),
            receivedArgument: () => receivedArgument
        };
    };

It gives me Cannot find name 'T'. error for the line where I declare receivedArgument variable let receivedArgument: T;

When I declare the same function with non-arrow (normal) function syntax, then everything works fine:

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

    function singleArgumentSpy<T>() : {
        fn: (arg: T) => void, 
        receivedArgument: () => T
    } {
        let receivedArgument: T;
        return {
            fn: (arg) => (receivedArgument = arg),
            receivedArgument: () => receivedArgument
        };
    };

Could you tell me why does the arrow function declaration give me the error?

>Solution :

It works if you add a <T> (or <T,> if JSX is enabled) before the arrow function definition, and an arg: T annotation in fn so it knows it must be the same T:

TS Playground link

const singleArgumentSpy: <T>() => {
    fn: (arg: T) => void, 
    receivedArgument: () => T
} = <T,>() => {
    let receivedArgument: T;
    return {
        fn: (arg: T) => (receivedArgument = arg),
        receivedArgument: () => receivedArgument
    };
};
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