【问题标题】:Typescript: parameter 'error' implicitly has an 'any' type打字稿:参数“错误”隐式具有“任何”类型
【发布时间】:2018-11-30 09:50:14
【问题描述】:

使用打字稿的第一天,我遇到了〜逻辑错误?

server.ts

interface StopAppCallback {
    (err: Error | null): void
}

interface StartAppCallback {
    (err: Error | null, result?: Function): void
}

export default (startCb: StartAppCallback): void => {
    const stopApp = (stopCb: StopAppCallback): void => {
        return stopCb(null)
    }

    return startCb(null, stopApp)
}

boot.ts

import server from './src/server'

server((err, stopApp) => { //<-- no error
    if (err) {
        throw err
    }

    if (typeof stopApp !== 'function') {
        throw new Error('required typeof function')
    }

    stopApp((error) => { //<-- tsc error
        if (error) {
            throw error
        }
    })
})

tsc 错误:参数 'error' 隐式具有 'any' 类型

我不明白,接口的定义和设置方式相同。那么交易是什么? 在设置中关闭 noImplicitAnystrict 或添加 :any 是无效的。

我在 tsc 逻辑中有什么不明白的地方?还是我定义有问题?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    问题是你没有在 箭头函数。

    例如:

    let printing=(message)=>{
        console.log(message);
    }
    

    这会导致错误

    • 错误 TS7006:参数“消息”隐含地具有“任何”类型。

    正确的做法是:

    let printing=(message:string )=>{
        console.log(message);
    }
    

    【讨论】:

      【解决方案2】:

      问题在于StartAppCallback 接口,将result? 定义为Function。传递给stopApp 的回调变为Function 类型。具有该类型的函数的参数没有任何明确的类型,因此会出现错误。一个更简单的例子:

      // this will give the error you're dealing with now
      const thing: Function = (arg) => arg
      

      解决方案:将result 定义为实际内容:

      interface StartAppCallback {
        (err: Error | null, result?: (stopCb: StopAppCallback) => void): void
      }
      

      作为一般规则,尽可能避免使用Function 类型,因为它会导致代码不安全。

      【讨论】:

        【解决方案3】:

        在代码中添加类型,例如

        server((err: String, stopApp) => { //<-- added String type
        

        【讨论】:

          猜你喜欢
          • 2021-03-29
          • 2021-11-17
          • 2017-08-21
          • 2019-11-11
          • 1970-01-01
          • 2018-08-15
          • 1970-01-01
          • 2019-07-07
          相关资源
          最近更新 更多