Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS compilation - "noImplicitAny" doesn't work

I have the code

let z;
z = 50;
z = 'z';

and my tsconfig.json is:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "sourceMap": false,
    "noEmitOnError": true,
    "strict": true,
    "noImplicitAny": true
  }
}

But what the hell it is that there's no exceptions throgh compiling to js?

Best Regards, Crova

like image 353
Crova Avatar asked Jul 27 '17 12:07

Crova


People also ask

How do I turn on noImplicitAny?

noImplicitAny Example You can stop this behavior by enabling the compiler flag noImplicitAny . To enable open the tsconfig file and add the "noImplicitAny":true under the compilerOptions . Now the above function will throw the compiler error. Parameter 'n' implicitly has an 'any' type.

Should you use noImplicitAny?

Using noImplicitAny is a good practice for any developer, no one will want to add datatypes everywhere when migrating from JavaScript to TypeScript codebase. So after we use noImplicitAny we have to explicitly add type at the time of the first scripting only so that it doesn't become a pain later.

What is include and exclude in Tsconfig?

The include and exclude properties take a list of glob-like file patterns. The supported glob wildcards are: * matches zero or more characters (excluding directory separators) ? matches any one character (excluding directory separators)


2 Answers

Because z is never typed as any. The type of z is simply inferred based on what you assign to it.

From the release notes:

With TypeScript 2.1, instead of just choosing any, TypeScript will infer types based on what you end up assigning later on.

Example:

let x;

// You can still assign anything you want to 'x'.
x = () => 42;

// After that last assignment, TypeScript 2.1 knows that 'x' has type '() => number'.
let y = x();

// Thanks to that, it will now tell you that you can't add a number to a function!
console.log(x + y);
//          ~~~~~
// Error! Operator '+' cannot be applied to types '() => number' and 'number'.

// TypeScript still allows you to assign anything you want to 'x'.
x = "Hello world!";

// But now it also knows that 'x' is a 'string'!
x.toLowerCase();

So in your case:

let z;
z = 50;
let y = z * 10; // `z` is number here. No error
z = 'z';
z.replace("z", "")// `z` is string here. No error
like image 175
Saravana Avatar answered Sep 27 '22 20:09

Saravana


noImplicitAny literally means:

Trigger an error if TypeScript uses 'any' whenever it can't infer a type

In your case above at any point of your code compiler easily infer what is the type of z. And therefore it can check that the appropriate methods/props you are calling on z is allowed or not.

like image 20
Amid Avatar answered Sep 27 '22 21:09

Amid