Reputation: 583
I have the following typescript code :
let a;
a = "number";
let t = a.endsWith('r');
console.log(t);
Since a is not declared with a type, Compiler infers it as an 'any' type. Now when we assign string value to it and when we try to use 'endsWith' function against this value, why doesnt compiler give compile error since 'endsWith' is not a valid function for an 'any' type. I have observed it compiles / transpiles fine into a Js and executes successfully. I understand proper way to write the code is :
let a : string;
a = "number";
let t = a.endsWith('r');
console.log(t);
But Why does it compiles fine in the previously mentioned code block ?
Upvotes: 1
Views: 212
Reputation: 86
Any
opts out of the type system so you will not get compile errors for a.endsWith()
even if a
is actually another type. See https://www.typescriptlang.org/docs/handbook/basic-types.html#any
Upvotes: 3
Reputation: 352
Any type means the type will be decided at runtime. Which type of data it contains same will be the type of the variable. Example:
let someVariable: any ;
somVariable = 1000;
somVariable's type will be read as a number at run-time.
somVariable = "string";
if somVariable contains a string the type will be read as a string at run-time.
The type mismatch error will be generated at run-time if there is a mismatch because the type is decided at run-time of any.
Upvotes: 1
Reputation: 583
Any data type is like dynamic type from C# where it checks the methods assigned after the dot at run time only. So at compile time- read coding, you can assign anything to it and it will pass the compilation. Only at run time, it will check whether the methods attached are genuinely available and if not it will give run time error.
Upvotes: 1