Search code examples
typescriptvisual-studio-codetsconfig

Typescript noImplicitAny and noImplicitReturns not working as expected


I have added the "noImplicitAny" and "noImplicitReturns" to my Typescript tsconfig.json file:

{
    "compilerOptions": {
        "target":"es5",
        "noImplicitAny": true,
        "noImplicitThis": true,
        "noImplicitReturns": true,
        "noUnusedLocals":true,
        "out": "dist/js/main.js"
    }
}

I expected that the following code would generate errors, or at least warnings:

private randomMove() {  // no return type but no warning :(
    let o = 3;          // no type for o but no warning :(
}

The "noUnusedLocals" IS working.

Is this how it's supposed to work, am I missing something? Is it possible to have Visual Studio Code generate warnings when you don't specify types / return types?


Solution

  • You misunderstood what those flags mean.

    noImplicitAny:

    Raise error on expressions and declarations with an implied any type.

    This isn't the case in your example because the compiler infers that the type of o is number, you should get the error if you do:

    let o;
    

    noImplicitReturns:

    Report error when not all code paths in function return a value.

    Your function might not need to return at all, but doing this:

    function fn(a: number): boolean {
        if (a > 0) {
            return false;
        }
    }
    

    Should result in a compilation error.

    No, there's no way (that I'm aware of) that will cause the compiler to error if a function doesn't include a return type.
    That's because:

    1. The compiler can infer the return type itself most of the time
    2. What if your function doesn't return? It would be way too verbose for a lot of people to need to annotate each function with : void