Using the typescript playground with noImplicitAny turned on, I enter this code:
async function a () {
const b = JSON.parse('{"a":"x"}');
console.log(b)
}
If I hover over the "b" on the second line, I see that its type is inferred as any. However, there is no error. Am I misunderstanding what noImplicitAny is supposed to do or is this a bug?
The --noImplicitAny compiler option produces warnings only in places where type inference fails, and it falls back or defaults to any. For example, you get an implicit-any error when a function parameter cannot be contextually typed:
const f = (arg) => arg + 1; // error!
// ------> ~~~ implicit any
You also get such an error if an auto-typed variable (see microsoft/TypeScript#11263) cannot be inferred by the compiler via control flow, such as if the variable is referenced in separate function scope:
let w; // error!
// >~ implicit any
w = 2;
function foo() { w } // implicit any
These are situations where the compiler says "I don't know what's going on here so I'll give it an any type".
On the other hand, if you call a function whose return type is any, you will get a value of type any. This might be an "implicit" any in the sense that the caller of the function does not need to write out the return type, but it isn't due to a failure of type inference. On the contrary, when a variable you assign that to is inferred as any, it's a success of type inference (just like x being a number in const x = 1 + 2 indicates successful inference). So there's no implicit-any error in these situations.
And since the TypeScript library typings for JSON.parse() looks like
interface JSON {
parse(text: string, reviver?: (this: any, k: string, v: any) => any): any;
}
then
const b = JSON.parse('{"a":"x"}');
successfully infers any for the type of b and there is no compiler warning.
Playground link to code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With