Reputation: 75
First day with typescript and i got ~logic error?
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: parameter 'error' implicitly has an 'any' type
I don't get it, interfaces are defined and set in same way. So whats the deal? Turning off noImplicitAny and strict in settings or adding :any is dum.
What i don't understand in tsc logic? Or i am defining something wrong?
Upvotes: 3
Views: 21813
Reputation: 484
The problem is that you didn't add the the type of the passed parameter in the Arrow function.
For example:
let printing=(message)=>{
console.log(message);
}
This will cause an error
- error TS7006: Parameter 'message' implicitly has an 'any' type.
The correct way is:
let printing=(message:string )=>{
console.log(message);
}
Upvotes: 1
Reputation: 12018
The problem is with the StartAppCallback
interface, defining result?
as Function
. The callback passed to stopApp
becomes the type Function
. Functions with that type don't have any definite type for their arguments, hence the error. A simpler example:
// this will give the error you're dealing with now
const thing: Function = (arg) => arg
Solution: define result
as what it actually is:
interface StartAppCallback {
(err: Error | null, result?: (stopCb: StopAppCallback) => void): void
}
As a general rule, try to avoid the Function
type whenever possible, as it leads to unsafe code.
Upvotes: 4
Reputation: 6692
Add type to your code, for example
server((err: String, stopApp) => { //<-- added String type
Upvotes: 0