Typescript: Required callback parameters?

后端 未结 2 1333
别跟我提以往
别跟我提以往 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条回答
  •  萌比男神i
    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)
    

提交回复
热议问题