3

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

Comments

0

Add type to your code, for example

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.