Search code examples
javascripttypescripttypescript-types

Why there is no compile time error when 'string' functions are used on an 'any' field type variable in TypeScript?


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 ?


Solution

  • 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