Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript noImplicitAny not causing an error

Tags:

typescript

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?

like image 908
Matt Broatch Avatar asked Jun 29 '26 21:06

Matt Broatch


1 Answers

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

like image 100
jcalz Avatar answered Jul 01 '26 11:07

jcalz



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!