TypeScript

Top 20 TypeScript Interview Questions and Answers with Examples

Prepare for TypeScript interviews with 20 questions covering type inference, interfaces, unions, generics, narrowing, utility types, strict mode, async code and React typing.

This TypeScript interview preparation guide focuses on understanding each concept, explaining when it matters, and supporting your answer with a practical example. Use it as a revision checklist and practise explaining the ideas in your own words.

How to use this guide: Try answering each question aloud before opening the explanation. Then adapt the example to a real application or project you have worked on.

1. What is TypeScript, and how is it different from JavaScript?

Answer: TypeScript is a typed superset of JavaScript that adds static type checking and language tooling. TypeScript code is compiled or transpiled to JavaScript for execution in browsers and JavaScript runtimes. Types are primarily a development-time feature and are erased from the emitted JavaScript. TypeScript helps catch many mistakes before runtime, but it does not validate external data automatically.

Example

function greet(name: string): string {
  return `Hello, ${name}`;
}

2. What is type inference in TypeScript?

Answer: Type inference means TypeScript can determine a variable or expression’s type from its initial value and usage. This reduces the need to annotate every variable. Explicit annotations are useful at public API boundaries, function parameters and places where inference would be too broad or unclear. Inference does not make TypeScript dynamically change a variable’s type later.

Example

const count = 10;      // inferred number
const names = ["Ada", "Linus"]; // inferred string[]
function total(a: number, b: number) { return a + b; }

3. What is the difference between any, unknown and never?

Answer: any disables most type checking for a value and can allow unsafe operations. unknown can hold any value but must be narrowed or checked before use, making it safer for untrusted input. never represents values that should not occur, such as a function that always throws or an exhaustive switch branch that cannot be reached.

Example

function printValue(value: unknown) {
  if (typeof value === "string") console.log(value.toUpperCase());
}
function fail(message: string): never { throw new Error(message); }

4. What is a union type?

Answer: A union type allows a value to be one of several specified types. Code can use only members that are common to all union constituents until a type guard narrows the value. Unions are useful for representing states such as loading, success and error, or values that can arrive in multiple formats.

Example

type Status = "pending" | "approved" | "rejected";
function setStatus(status: Status) { /* ... */ }

5. What is an intersection type?

Answer: An intersection type combines multiple types so a value must satisfy all of them. It is useful for composing object capabilities or extending a base shape without declaring a new interface. Intersections can become difficult to read if combined properties conflict, so use them deliberately.

Example

type HasId = { id: number };
type HasName = { name: string };
type Customer = HasId & HasName;

6. What is the difference between interface and type?

Answer: Both can describe object shapes and are commonly interchangeable for simple contracts. Interfaces support declaration merging and can be extended with extends. Type aliases can describe unions, intersections, primitives, tuples and mapped or conditional types. Teams often use interfaces for object contracts and type aliases for unions or composed types, but consistency matters more than a universal rule.

Example

interface User { id: number; name: string; }
type Result = { ok: true; data: User } | { ok: false; error: string };

7. What are generics in TypeScript?

Answer: Generics let a function, interface or class work with different types while preserving type information. A type parameter acts as a placeholder that is chosen when the generic is used or inferred from its arguments. Constraints can require a generic type to support particular properties or behaviour.

Example

function first<T>(items: T[]): T | undefined {
  return items[0];
}
const user = first([{ id: 1 }]);

8. What are utility types such as Partial, Pick and Omit?

Answer: Utility types transform existing types. Partial makes all properties optional, Pick selects a subset of properties, and Omit removes selected properties. Readonly prevents reassignment of properties through that type. These tools reduce duplicated declarations and help express API-specific shapes, though they do not perform runtime transformation or validation.

Example

type User = { id: number; name: string; email: string };
type UserUpdate = Partial<Pick<User, "name" | "email">>;
type PublicUser = Omit<User, "email">;

9. What are optional properties and optional chaining?

Answer: An optional property is marked with ? and may be missing or undefined. Optional chaining uses ?. to safely access a property or call a method only when the value before it is not nullish. It prevents some null-reference errors, but the result may itself be undefined and still needs handling.

Example

type Profile = { name: string; manager?: { name: string } };
const managerName = profile.manager?.name ?? "Not assigned";

10. What is strictNullChecks?

Answer: When strictNullChecks is enabled, null and undefined are not automatically assignable to every type. Code must explicitly handle the possibility that a value is absent. This catches many runtime errors at compile time and encourages clear contracts. The strict compiler option enables strictNullChecks along with several other checks.

Example

function findUser(id: number): User | undefined { /* ... */ }
const user = findUser(5);
if (user) console.log(user.name);

11. What is an enum, and what alternatives are available?

Answer: An enum defines a named set of values and can be numeric or string-based. For many application states, a string-literal union or an object with as const is simpler and emits less runtime code. Choose based on interoperability, readability and how the values must be used at runtime.

Example

const Roles = { Admin: "admin", Reader: "reader" } as const;
type Role = typeof Roles[keyof typeof Roles];

12. What are type guards and narrowing?

Answer: A type guard is a runtime check that lets TypeScript narrow a broad type to a more specific type. Common guards include typeof, instanceof, property checks with in and user-defined predicate functions. Narrowing helps safely access properties that exist only on one union member.

Example

function format(value: string | number) {
  if (typeof value === "number") return value.toFixed(2);
  return value.trim();
}

13. What is keyof in TypeScript?

Answer: keyof produces a union of the property keys of a type. It is useful for writing reusable functions that safely access known fields and for building mapped types. Combined with generics, it helps keep a key linked to the type of its corresponding value.

Example

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

14. What is an indexed access type?

Answer: An indexed access type retrieves the type of a property or array element from another type. The syntax T[K] means the type of property K in T. It is useful when function return types or other declarations need to stay connected to the source model rather than duplicating types manually.

Example

type User = { id: number; profile: { city: string } };
type Profile = User["profile"];
type City = User["profile"]["city"]; // string

15. What are mapped types?

Answer: Mapped types create a new type by iterating over the keys of an existing type and transforming each property. Built-in types such as Partial and Readonly are based on mapped-type capabilities. They are useful for creating consistent variations of domain or API types.

Example

type Nullable<T> = { [K in keyof T]: T[K] | null };
type NullableUser = Nullable<{ id: number; name: string }>;

16. What are conditional types?

Answer: Conditional types select a type based on whether one type extends another. They use the form T extends U ? X : Y and can distribute over union types when the checked type is a naked type parameter. They are powerful for reusable type utilities, but overly complex conditional types can make code difficult to understand.

Example

type MessageOf<T> = T extends { message: unknown } ? T["message"] : never;
type A = MessageOf<{ message: string }>; // string

17. What does readonly mean in TypeScript?

Answer: readonly prevents a property from being reassigned through a reference typed with that declaration. It is a compile-time restriction, not a runtime freeze. For arrays, ReadonlyArray or readonly array syntax prevents mutation through that variable. Use readonly to express ownership and immutability expectations in APIs.

Example

type Config = { readonly apiBaseUrl: string };
const tags: readonly string[] = ["react", "typescript"];

18. What are function overloads in TypeScript?

Answer: Function overloads let callers use multiple signatures while the implementation handles the supported cases. The overload signatures describe the public call patterns, and the implementation signature must be compatible with all of them. Use overloads when input types map to clearly different result types; otherwise a union parameter may be simpler.

Example

function parse(value: string): Date;
function parse(value: number): Date;
function parse(value: string | number): Date {
  return new Date(value);
}

19. What is structural typing?

Answer: TypeScript primarily uses structural typing: compatibility depends on the members a value has, not the declared name of its type. Two separately declared object types can be compatible if their required members match. This makes JavaScript libraries easier to model, but can mean that similarly shaped values are interchangeable even when the domain treats them as distinct.

Example

type Point = { x: number; y: number };
function draw(point: Point) {}
const location = { x: 10, y: 20, label: "A" };
draw(location);

20. Why should tsconfig strict mode be enabled?

Answer: Strict mode enables a group of stronger type-checking options, including strictNullChecks and noImplicitAny. It helps catch missing types and unsafe assumptions earlier. Enabling strict mode on an existing project may reveal many issues, so teams can turn it on in stages and resolve warnings systematically rather than weakening the configuration without understanding the cause.

Example

{
  "compilerOptions": {
    "strict": true,
    "noEmit": true
  }
}

How to prepare for your interview

Do not memorise definitions word for word. Practise explaining the concept in your own words, describe when you would use it, and mention one trade-off or common mistake. For coding and database topics, write the example yourself and test the edge cases.

Use this guide as a revision checklist, then review the topics you find difficult in more depth. Interview discussions often move from fundamentals to project decisions, debugging and performance scenarios.

Keep learning with DotNetRevision. Explore the ebook library for structured study guides, interview preparation and practical professional-development resources.

Browse DotNetRevision ebooks →

CONTINUE LEARNING

More interview preparation guides

Explore related C#, .NET, EF Core, React, TypeScript and SQL Server topics.

Browse all interview guides →