1. Can you explain the concept of type inference in TypeScript and provide an example of how it works?

Advanced

1. Can you explain the concept of type inference in TypeScript and provide an example of how it works?

Overview

Type inference in TypeScript is a powerful feature that allows the compiler to automatically deduce the types of variables and expressions based on their initial values or how they are used. This capability makes TypeScript code more concise and easier to maintain, as developers don't need to explicitly annotate types in many cases. Understanding type inference is crucial for writing effective TypeScript code and leveraging the full power of the language's type system.

Key Concepts

  1. Automatic Type Deduction: TypeScript can infer variable types based on initial assignment.
  2. Contextual Typing: TypeScript uses the context in which a variable is used to infer its type, such as in function parameters or return values.
  3. Best Common Type: When dealing with arrays or multiple types, TypeScript chooses the best common type that accommodates all members.

Common Interview Questions

Basic Level

  1. What is type inference in TypeScript?
  2. How does TypeScript infer the type of a variable when initialized?

Intermediate Level

  1. How does contextual typing work in TypeScript?

Advanced Level

  1. Can you explain how TypeScript decides on the best common type in arrays with elements of different types?

Detailed Answers

1. What is type inference in TypeScript?

Answer: Type inference in TypeScript refers to the compiler's ability to automatically deduce the types of variables, parameters, and return values based on the assigned values or how they are used within the code. This feature reduces the need for explicit type annotations, making the code cleaner and easier to maintain.
Key Points:
- Reduces the need for explicit type annotations.
- Makes code more concise and readable.
- Helps in catching type-related errors during compilation.

Example:

let message = "Hello, TypeScript"; // Type inferred as string
let numbers = [1, 2, 3];           // Type inferred as number[]
let mixed = [1, 'two', 3];         // Type inferred as (string | number)[]

function sum(a, b) {
  return a + b;                    // Return type inferred based on operation
}

2. How does TypeScript infer the type of a variable when initialized?

Answer: When a variable is initialized in TypeScript, the compiler looks at the value assigned to the variable and uses that value to determine the variable's type. If the variable is assigned a string, number, boolean, object, or any other value, TypeScript will use that initial assignment to infer the variable's type. This inferred type will then be used to check for type compatibility in later code.
Key Points:
- Inference is based on initial assignment.
- The inferred type is used for type checking throughout the code.
- No explicit type annotation is needed for the compiler to infer the type.

Example:

let isActive = true;               // Type inferred as boolean
let userId = "user_123";           // Type inferred as string
let scores = [10, 20, 30];         // Type inferred as number[]

// Usage in a function
function toggleActive(status) {
  isActive = !status;              // TypeScript knows `status` is a boolean
}

3. How does contextual typing work in TypeScript?

Answer: Contextual typing in TypeScript occurs when the type of an expression is implied by its location within the code. For example, when passing arguments to a function or determining a function's return type, TypeScript uses the context in which these variables are used to infer types, making explicit type annotations unnecessary in many cases.
Key Points:
- Uses the context of an expression to infer type.
- Applies to function arguments, return types, and event handlers.
- Helps in maintaining consistency in type usage across related operations.

Example:

window.onmousedown = function(mouseEvent) {
  console.log(mouseEvent.button);  // `mouseEvent` implicitly has type `MouseEvent`
};

function combine(a: number, b: number): number { // Contextually types the return
  return a + b;
}

4. Can you explain how TypeScript decides on the best common type in arrays with elements of different types?

Answer: When an array in TypeScript contains elements of different types, TypeScript uses an algorithm to determine the "best common type" that can accommodate all the elements in the array. It examines all possible candidates and selects the type that covers all the array elements. If no such common type is found, the array is typed as a union of all the element types.
Key Points:
- Examines all element types in the array.
- Chooses a common type that fits all elements, if possible.
- Falls back to a union type if no single best common type is found.

Example:

let mixedArray = [0, "one", false];  // Type inferred as (number | string | boolean)[]
let numbers = [1, 2.5, 3];          // Type inferred as number[] since all elements are numbers

This explanation covers the concept of type inference in TypeScript, providing a solid understanding through examples and key points relevant to interview preparation.