TS Explicit & Inference

Explicit Types & Inference

TypeScript provides two main ways to assign types to your variables.

You can be explicit by writing out the exact type yourself.

Alternatively, you can let TypeScript infer the type automatically.

Both methods are excellent for ensuring code is readable and maintainable.


1. Explicit Typing

Explicit typing means writing out the type directly after the variable name.

This clearly documents your intentions for other developers reading the code.

It is highly recommended for complex structures to ensure complete safety.

Explicit Example:

let username: string = "IntricateDevo";

// We explicitly stated this is a string let totalUsers: number = 500;

console.log("User:", username, "| Total:", totalUsers);


2. Type Inference

Type inference is when TypeScript guesses the type based on the assigned value.

If you assign a number, TypeScript automatically knows the variable is a number.

This saves you time while keeping the exact same level of static type safety.

Inference Example:

let city = "New York"; // Inferred as string

// city = 100; // This will throw an error! // TypeScript knows city must remain a string.

console.log("City inferred as:", city);


3. SEO and Best Practices

Using inference helps keep your code clean and significantly less cluttered.

However, explicit types are better for function return values for clarity.

Writing clean code leads to faster load times and better developer experiences.

Best Practice Example:

// Explicit on parameters and return type
function multiply(a: number, b: number): number {
  return a * b; // Inference can also figure out the return type
}

let result = multiply(5, 10); console.log("Result:", result);


Exercise

?

What does type inference mean in TypeScript?


4. Final Thoughts

Mixing explicit typing and inference gives you the best of both worlds.

Use inference for simple variables, and explicit types for complex functions.

Next, we will look at some of TypeScript's special unique types!