Typescript not checking function argument types declared by interfaces

前端 未结 1 541
旧巷少年郎
旧巷少年郎 2021-01-12 07:26

I was expecting TWO errors when compiling the code below, but typescript compiles it without any errors.

interface IFoo{
    Bar(callback: (arg:string) =>         


        
1条回答
  •  广开言路
    2021-01-12 08:31

    This is answered in the TypeScript FAQ. Here is the text of that answer:

    This is the expected and desired behavior. First, refer to the "substitutability" primer at the top of the FAQ -- handler is a valid argument for callback because it can safely ignored extra parameters.

    Second, let's consider another case:

    let items = [1, 2, 3];
    items.forEach(arg => console.log(arg));
    

    This is isomorphic to the example that "wanted" an error. At runtime, forEach invokes the given callback with three arguments (value, index, array), but most of the time the callback only uses one or two of the arguments. This is a very common JavaScript pattern and it would be burdensome to have to explicitly declare unused parameters.

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