Typescript: Required callback parameters?

后端 未结 2 1300
别跟我提以往
别跟我提以往 2020-12-21 05:58

I want to define a function which takes a callback as a parameter, and that callback\'s parameters should be required. Typescript correctly reports a callback with a mismatc

相关标签:
2条回答
  • 2020-12-21 06:36

    There isn't a way to do this.

    Callbacks with fewer parameters than the caller provides are extremely common in JavaScript - functions like forEach, map, filter, etc all provide 3 or more arguments but are frequently given 1-parameter functions as callbacks.

    0 讨论(0)
  • 2020-12-21 06:48

    You could define a type for the handler. Now you can only pass a callback that has a string argument.

    // define a handler so you can use it for callbacks
    type Handler = (t: string) => void;
    
    function doSomething(t: string): void {
        console.log("hello " + t)
    }
    
    function thisFirst(callback: Handler) {
      callback('world') // ok
      callback(4) // not assignable to type 'string'
    }
    
    thisFirst(doSomething)
    
    0 讨论(0)
提交回复
热议问题