Implicit – TypeScript will infer the type based on the assigned value:
let firstName = “Dylan”; |
Note: When TypeScript “guesses” the type of a value, this is known as type inference. |
Implicit type assignment allows TypeScript to infer the type from the value. It is shorter, quicker to write, and often used during development and testing.
TypeScript generates an error when there is a mismatch in data types.
let firstName: string = “Dylan”; // type string firstName = 33; // attempts to re-assign the value to a different type |
Implicit type assignment would have made it less obvious that firstName is a string, but both will still result in an error.
let firstName = “Dylan”; // inferred to type string firstName = 33; // attempts to re-assign the value to a different type |
JavaScript does not produce an error for type mismatches.
TypeScript may not always accurately infer a variable’s type. In such cases, it assigns the type any, which disables type checking.
// Implicit any as JSON.parse doesn’t know what type of data it returns so it can be “any” thing… const json = JSON.parse(“55”); // Most expect json to be an object, but it can be a string or a number like this example console.log(typeof json); |
This behavior can be prevented by enabling the noImplicitAny option in a project’s tsconfig.json. This JSON configuration file allows you to customize certain aspects of how TypeScript functions.