Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

前端 未结 8 1009
刺人心
刺人心 2020-11-30 17:19

Currently I have type definition as:

interface Param {
    title: string;
    callback: any;
}

I need something like:

inter         


        
8条回答
  •  借酒劲吻你
    2020-11-30 17:24

    Typescript: How to define type for a function callback used in a method parameter?

    You can declare the callback as 1) function property or 2) method:

    interface ParamFnProp {
        callback: (a: Animal) => void; // function property
    }
    
    interface ParamMethod {
        callback(a: Animal): void; // method
    }
    

    There is an important typing difference since TS 2.6:

    You get stronger ("sound") types in --strict or --strictFunctionTypes mode, when a function property is declared. Let's take an example:

    const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
    const dogCallback = (d: Dog): void => { } 
    
    // function property variant
    const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
    const param12: ParamFnProp = { callback: animalCallback } // works
    
    // method variant
    const param2: ParamMethod = { callback: dogCallback } // now it works again ...
    

    Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array.

    Summary

    • There is a type difference between function property and method declaration
    • Choose a function property for stronger types, if possible

    Playground sample code

提交回复
热议问题