Variables and Type Inference in TypeScript Explained with Examples - Textnotes

Variables and Type Inference in TypeScript Explained with Examples


Learn how variables work in TypeScript, including let and const, explicit and implicit typing, and best practices for using TypeScript’s powerful type inference system in real-world applications.

1. Let and Const

TypeScript uses let and const for variable declarations, just like modern JavaScript.

Let

let is used when the value of a variable may change.

Example:


let count: number = 10;
count = 20;

let has block scope and is safer than the older var keyword.

Const

const is used when the value should not be reassigned.

Example:


const appName: string = "Inventory System";
// appName = "HR System"; Error

With const, the variable reference cannot change, but object properties can still be modified.

Example:


const user = {
name: "Muni",
age: 35
};

user.age = 36;

2. Explicit Typing

Explicit typing means manually specifying the type of a variable.

When to Use Explicit Typing

  1. Function parameters
  2. Function return types
  3. Variables with unclear initial values
  4. Public APIs and shared code

Example


let username: string;
username = "Muni";

let totalAmount: number = 5000;

Explicit typing improves readability and prevents accidental type changes.

3. Implicit Typing (Type Inference)

TypeScript automatically infers the type of a variable based on its initial value. This is known as type inference.

Example


let city = "Mumbai";
let age = 35;

TypeScript infers:

  1. city as string
  2. age as number

Attempting to assign a different type later will result in an error.

Example:


age = "thirty five";

Type inference reduces code verbosity while maintaining type safety.

4. Best Practices

Use const by default and switch to let only when reassignment is required. Avoid using var.

Rely on implicit typing when the inferred type is clear and obvious. Use explicit typing when the type is not immediately clear or when working with function signatures and APIs.

Avoid using the any type unless absolutely necessary. Prefer unknown when handling uncertain data.

Enable strict mode in tsconfig.json to enforce consistent typing and prevent hidden bugs.

Keep variable scope as small as possible to improve maintainability and reduce errors.

Conclusion

Variables and type inference are core concepts in TypeScript. By understanding when to use explicit typing and when to rely on inference, developers can write clean, safe, and maintainable code suitable for real-world applications.