Type Inference

Basics

TypeScript can infer types automatically in many cases.

Code Example

let message = "Hello, TypeScript!";
console.log(typeof message); // Output: string

Explanation

Type inference is a powerful feature in TypeScript that allows the compiler to automatically determine the type of a variable based on its value. This reduces the need for explicit type annotations, making the code cleaner and more concise. The compiler analyzes the context and usage of variables to infer their types accurately.

Best Practices

  • Let TypeScript infer types when they are obvious to reduce verbosity.
  • Use explicit type annotations when the inferred type might not be what you expect.
  • Leverage type inference in function return types when possible.
  • Be aware that type inference works differently for object literals and might require type assertions in some cases.