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

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

Currently I have type definition as:

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

I need something like:

inter         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 17:38

    Here's an example of a function that accepts a callback

    const sqk = (x: number, callback: ((_: number) => number)): number => {
      // callback will receive a number and expected to return a number
      return callback (x * x);
    }
    
    // here our callback will receive a number
    sqk(5, function(x) {
      console.log(x); // 25
      return x;       // we must return a number here
    });
    

    If you don't care about the return values of callbacks (most people don't know how to utilize them in any effective way), you can use void

    const sqk = (x: number, callback: ((_: number) => void)): void => {
      // callback will receive a number, we don't care what it returns
      callback (x * x);
    }
    
    // here our callback will receive a number
    sqk(5, function(x) {
      console.log(x); // 25
      // void
    });
    

    Note, the signature I used for the callback parameter ...

    const sqk = (x: number, callback: ((_: number) => number)): number

    I would say this is a TypeScript deficiency because we are expected to provide a name for the callback parameters. In this case I used _ because it's not usable inside the sqk function.

    However, if you do this

    // danger!! don't do this
    const sqk = (x: number, callback: ((number) => number)): number

    It's valid TypeScript, but it will interpreted as ...

    // watch out! typescript will think it means ...
    const sqk = (x: number, callback: ((number: any) => number)): number

    Ie, TypeScript will think the parameter name is number and the implied type is any. This is obviously not what we intended, but alas, that is how TypeScript works.

    So don't forget to provide the parameter names when typing your function parameters... stupid as it might seem.

提交回复
热议问题