In my tsconfig.json I have set "noImplicitAny": true
. However the following code doesn't produce an error:
let x;
x = 5;
x = "a";
x = null;
console.log(x);
Isn't x
implicitly set to any
here (as opposed to explicitly, where I would write let x: Any;
)?
I understand that, because of the different assignments, the compiler can infer Any
at compile time here, but I thought the option "noImplicitAny": true
is used to prevent this inference.
Is there some other compiler option to show an error in this case?
Typescript may infer a variable to be a subtype of its actual type depending on context:
let a: number | number[] = 0;
if (!Array.isArray(a)) a = [a];
void a;
// ^?
// let a: number[] | (number & any[])
a = 123;
void a;
// ^?
// let a: number
if (a === 999) {
void a;
// ^?
// let a: 999
}
function f() {
// doesn't work in functions:
void a;
// ^?
// let a: number | number[]
}
If you define variable type as unknown
subtyping will stop working for assignements.
If you define variable type as any
subtyping will stop working for everywhere.
If you won't write the type it'll be taken from the value you assigned.
If you however don't define variable type at all, it'll be a subtypeable any