Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: parameter 'error' implicitly has an 'any' type

Tags:

typescript

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?

like image 771
someone from belgium is called Avatar asked Mar 05 '26 20:03

someone from belgium is called


2 Answers

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.

like image 89
kingdaro Avatar answered Mar 08 '26 08:03

kingdaro


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);
}
like image 40
N.Elsayed Avatar answered Mar 08 '26 10:03

N.Elsayed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!