TypeScript: Is there a way to typecheck function arity?

后端 未结 2 458
暖寄归人
暖寄归人 2020-12-04 02:19

Given the following code:

type Function0 = () => T;
type Function1 = (arg1: A1) => T;
type Function2 = (arg1: A1         


        
2条回答
  •  时光说笑
    2020-12-04 03:16

    This

    const foo: Function1 = () => "hi there";
    

    is no different from a function that declares, but does not use its arguments:

    const foo_anyway: Function1 = (arg1: any) => "hi there";
    

    In Javascript, you will get no error if you call foo_anyway without arguments.

    So it does not make sense to report errors about function values that are actually compatible with declared type.

    On the other hand, if it needs more arguments, it becomes incompatible and the error is reported if you turn on --strictFunctionTypes (compatibility rules for function types in TypeScript are even less strict by default, see function parameter bivariance)

    const foo_error: Function1 = (arg1: any, arg2: string) => "hi there";
    
    //Type '(arg1: any, arg2: string) => string' is not assignable 
    // to type 'Function1'.
    

提交回复
热议问题