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

前端 未结 8 1020
刺人心
刺人心 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:23

    There are four abstract function types, you can use them separately when you know your function will take an argument(s) or not, will return a data or not.

    export declare type fEmptyVoid = () => void;
    export declare type fEmptyReturn = () => any;
    export declare type fArgVoid = (...args: any[]) => void;
    export declare type fArgReturn = (...args: any[]) => any;
    

    like this:

    public isValid: fEmptyReturn = (): boolean => true;
    public setStatus: fArgVoid = (status: boolean): void => this.status = status;
    

    For use only one type as any function type we can combine all abstract types together, like this:

    export declare type fFunction = fEmptyVoid | fEmptyReturn | fArgVoid | fArgReturn;
    

    then use it like:

    public isValid: fFunction = (): boolean => true;
    public setStatus: fFunction = (status: boolean): void => this.status = status;
    

    In the example above everything is correct. But the usage example in bellow is not correct from the point of view of most code editors.

    // you can call this function with any type of function as argument
    public callArgument(callback: fFunction) {
    
        // but you will get editor error if call callback argument like this
        callback();
    }
    

    Correct call for editors is like this:

    public callArgument(callback: fFunction) {
    
        // pay attention in this part, for fix editor(s) error
        (callback as fFunction)();
    }
    

提交回复
热议问题