Why doesn't TypeScript enforce a generic parameter in callback?

后端 未结 1 681
不知归路
不知归路 2021-01-14 11:14

Consider this TypeScript code, compiled with 2.6.1:

function foo (bar: T, baz: (T) => void) {
    const test: T = bar;
    baz(test);
}

const st         


        
相关标签:
1条回答
  • 2021-01-14 11:53

    Well, because T in baz: (T) => void is not a type name, it's a parameter name.

    When you fix the syntax to mean what you want it to mean, you get the expected error:

    function foo<T> (bar: T, baz: (t: T) => void) {
        const test: T = bar;
        baz(test);
    }
    
    const s: string = "a";
    foo(s, num => num.parseInt()); 
    // Property 'parseInt' does not exist on type 'string'.
    

    Granted, it's really hard to spot errors like this one - I saw it only when I pasted your code into typescript playground and turned on --noImplicitAny. (T) immediately got highlighted with Parameter 'T' implicitly has an 'any' type. Even that error was puzzling for a moment - wait what - T is not a parameter, it's a type - ...!

    0 讨论(0)
提交回复
热议问题