Typescript:参数';错误';隐式具有';任何';类型
使用typescript的第一天,我遇到了~逻辑错误 server.tsTypescript:参数';错误';隐式具有';任何';类型,typescript,Typescript,使用typescript的第一天,我遇到了~逻辑错误 server.ts interface StopAppCallback { (err: Error | null): void } interface StartAppCallback { (err: Error | null, result?: Function): void } export default (startCb: StartAppCallback): void => { const stop
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)
}
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
}
})
})
boot.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)
}
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
}
})
})
从“./src/server”导入服务器
例如,服务器((err,stopApp)=>{/{/将类型添加到代码中
server((err: String, stopApp) => { //<-- added String type
server((错误:String,stopApp)=>{/问题在于StartAppCallback
接口,它将result?
定义为Function
。传递给stoppp
的回调将成为类型Function
。具有该类型的函数的参数没有任何确定的类型,因此会出现错误。一个简单的示例:
// this will give the error you're dealing with now
const thing: Function = (arg) => arg
let printing=(message)=>{
console.log(message);
}
解决方案:将结果定义为实际情况:
interface StartAppCallback {
(err: Error | null, result?: (stopCb: StopAppCallback) => void): void
}
作为一般规则,尽可能避免使用函数
类型,因为它会导致不安全的代码。问题在于您没有在
箭头功能
例如:
// this will give the error you're dealing with now
const thing: Function = (arg) => arg
let printing=(message)=>{
console.log(message);
}
这将导致错误
- 错误TS7006:参数“message”隐式具有“any”类型
正确的方法是:
let printing=(message:string )=>{
console.log(message);
}