Home > Net >  Why do Typescript arrow function generics not work as same as named function generics
Why do Typescript arrow function generics not work as same as named function generics

Time:12-31

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:

    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?

CodePudding user response:

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
    };
};
  • Related