WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Intermediate · question 40 of 100

Can you explain the concept of ’type inference’ in TypeScript?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

Type inference is a feature in TypeScript where the compiler automatically determines the data type of a variable or expression based on the information available at the time of compilation. In other words, the TypeScript compiler attempts to understand the type of a value to ensure that your code is type-safe without the need for explicit type annotations.

Type inference can be useful when declaring variables, setting default function parameters, or even determining the return type of a function. In many cases, type inference allows you to write more concise code while still maintaining type safety.

Let’s take a look at some examples to illustrate the concept of type inference in TypeScript.

1. Variable declaration:

let x = 5; // inferred to have the 'number' type
let y = 'hello'; // inferred to have the 'string' type

// Later in the code.
x = 10; // No errors, since 'x' is inferred to have the 'number' type
y = 'world'; // No errors, since 'y' is inferred to have the 'string' type

In this example, TypeScript compiler inferred the type of variables ‘x‘ and ‘y‘ based on the values assigned during their declaration.

2. Inferred return type of a function:

function sum(a: number, b: number) {
    return a + b;
}

In this case, TypeScript is able to infer that the return type of the ‘sum‘ function is also a ‘number‘ because the result of adding two numbers will always be a number.

3. Inferred type from context:

TypeScript also uses context to infer more specific types from wider types. For example:

type Animal = {
    species: string;
};

type Dog = Animal & {
    isPet: boolean;
};

function processAnimal(animal: Animal) {
    if ('isPet' in animal) {
        // 'animal' is now inferred to be of type 'Dog'
    }
}

In this case, TypeScript understands that inside the ‘if‘ block, ‘animal‘ must be an instance of the ‘Dog‘ type.

Type inference helps you maintain type safety and write cleaner, more concise code without the need for unnecessary explicit typing. However, in some situations, you might still want to provide explicit types to prevent subtle bugs or provide better documentation.

Here is a summary of Type Inference in TypeScript:


Type Inference ⇒ Automatic Type Determination

based on  Available Information

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics