100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
TypeScript

Common TypeScript Interview Questions

The most frequently asked TypeScript interview questions covering types, interfaces, generics, compilation, and tsconfig, with clear answers and code-tracing practice.

Interview PrepIntermediate16 min readJul 8, 2026
Analogies

1. Overview

This topic collects the TypeScript questions that show up most often in front-end and full-stack interviews. It covers the fundamentals — type annotations, interfaces, generics, the compiler, and tsconfig — mixed with short code-tracing exercises so you can practice reasoning about what the compiler will accept or reject. Read each question, try to answer it yourself before reading the explanation, and pay close attention to the code snippets: interviewers frequently ask you to predict a compiler error or the inferred type of a variable rather than just define a term.

🏏

Cricket analogy: Preparing for this topic is like a batter facing throwdowns before a big match -- practicing against annotations, interfaces, generics, and compiler quirks so the real "delivery" (interview question) doesn't catch you off guard.

2. Frequently Asked Questions

Q1. What is TypeScript and how does it relate to JavaScript?

TypeScript is a strongly typed superset of JavaScript developed by Microsoft that compiles down to plain JavaScript. Every valid JavaScript program is also valid TypeScript (with rare edge cases), and TypeScript adds optional static types, interfaces, generics, and modern syntax support on top. The TypeScript compiler (tsc) performs type checking at compile time and then erases all type annotations, producing ordinary JavaScript that runs unchanged in any JS engine.

🏏

Cricket analogy: TypeScript sits on top of JavaScript like a stricter domestic league sits on top of village cricket rules -- every legal village shot is still legal, but the league (tsc) adds extra checks first, then sets those extra rulebook pages aside for the actual game.

Q2. What is the difference between 'any' and 'unknown'?

'any' disables type checking entirely — you can call any method or access any property on an 'any'-typed value without the compiler complaining, which defeats the purpose of TypeScript. 'unknown' is the type-safe counterpart: a value of type 'unknown' can hold anything, but you cannot perform any operation on it until you narrow its type with a type guard (typeof, instanceof, or a custom check). 'unknown' forces you to prove the type before using it, so it should be preferred over 'any' whenever the type genuinely cannot be known in advance.

🏏

Cricket analogy: 'any' is like a groundskeeper who lets anyone onto the pitch without checking credentials -- chaos waiting to happen; 'unknown' is like a security guard who lets people through the gate but still checks ID before letting them near the wicket.

Q3. What will this code output or error on? interface Point { x: number; y: number; } const p: Point = { x: 1, y: 2, z: 3 };

This produces a compile-time error: 'Object literal may only specify known properties, and z does not exist in type Point.' This is TypeScript's 'excess property check', which only applies to object literals assigned directly to a typed variable. If the object were first assigned to a separate variable (const temp = { x: 1, y: 2, z: 3 }; const p: Point = temp;) it would compile, because excess property checks do not apply through an intermediate variable — only structural compatibility is checked in that case.

🏏

Cricket analogy: Handing the umpire a scorecard directly with an extra, unrecognized column ("z: 3") gets flagged immediately; but if you first write it in your notebook and copy just the recognized fields over, the umpire never sees the extra column.

Q4. What are generics and why are they useful?

Generics let you write reusable functions, classes, and interfaces that work over a variety of types while preserving type information, instead of resorting to 'any'. For example, function identity<T>(arg: T): T { return arg; } returns exactly the type it was given: identity<string>('hi') is typed as string, and identity(42) infers T as number automatically. Generics are the backbone of type-safe collections, utility types, and API client code where the shape of data varies by call site.

🏏

Cricket analogy: A generic pickPlayerOfMatch<T> function that works whether T is a batter's stats or a bowler's stats is like a single award ceremony format that adapts to crown either specialist without a separate ceremony written for each.

Q5. What is the difference between an interface and a type alias?

Both can describe the shape of an object, and in many cases they are interchangeable. Key differences: interfaces support declaration merging (declaring the same interface twice merges the members), while type aliases do not; interfaces can only describe object/function shapes (extended with 'extends'), while type aliases can also name unions, intersections, tuples, and primitives (type ID = string | number;); interfaces are generally preferred for public object APIs because of merging and clearer extension syntax, while type aliases are preferred for unions and complex compositions.

🏏

Cricket analogy: An interface BattingStats can be declared twice and TypeScript merges both, like two scorers' notes on the same innings combined into one official record; a type alias can't merge but can name a union like type MatchResult = "win" | "loss" | "tie" that an interface never could.

Q6. What does 'strict' mode in tsconfig.json actually enable?

'strict': true is a shorthand that turns on a family of stricter checks at once, including strictNullChecks (null and undefined are not assignable to other types unless explicitly included), noImplicitAny (variables/parameters without an inferable type raise an error instead of silently becoming 'any'), strictFunctionTypes, strictPropertyInitialization (class properties must be initialized or explicitly typed as possibly undefined), alwaysStrict, and a few others. Enabling strict mode is considered best practice for any serious TypeScript codebase because it catches an entire class of null-reference and implicit-any bugs at compile time.

🏏

Cricket analogy: Turning on strict: true is like a league mandating full DRS review, mandatory helmet checks, and pitch inspections all at once instead of leaving each optional -- it catches null-value "wides" and uninitialized-property "no-balls" before the match starts.

Q7. What is type inference, and what type does TypeScript infer here? let items = [1, 'two', 3];

Type inference is TypeScript's ability to determine a variable's type from its initializer without an explicit annotation. For 'let items = [1, "two", 3];' TypeScript infers the array type as (string | number)[] — a union array type — because the literal contains both number and string elements. If the array had used 'const' with a tuple-like structure and 'as const', TypeScript would instead infer a readonly tuple of literal types.

🏏

Cricket analogy: let scores = [45, "retired hurt", 12] infers as (string | number)[] since the array mixes numeric runs and text status, but writing it as const on a fixed historical scorecard would instead infer a readonly tuple of exact literal values.

Q8. What is a type guard, and how do discriminated unions use them?

A type guard is an expression that narrows a variable's type within a conditional branch, using constructs like typeof, instanceof, 'in', or a custom user-defined type predicate (function isFish(a: Fish | Bird): a is Fish). Discriminated unions combine a shared literal 'tag' property (e.g. kind: 'circle' | 'square') across each member of a union with a switch or if statement on that tag; TypeScript automatically narrows the type inside each branch based on the discriminant's value, enabling exhaustive, type-safe handling of each variant.

🏏

Cricket analogy: A discriminated union like { kind: "boundary" } | { kind: "wicket" } lets a scoring system switch on the kind tag the way a scorer instantly knows whether to update the boundary count or bowling figures based on a single shared field.

Q9. What is the purpose of the 'readonly' modifier and 'as const'?

'readonly' on an interface or class property prevents reassignment after initialization (a compile-time-only restriction — it does not freeze the object at runtime). 'as const' goes further: applied to a literal, it tells TypeScript to infer the narrowest possible literal types and make array/object properties readonly, e.g. const colors = ['red', 'green'] as const; infers readonly ['red', 'green'] instead of string[]. This is commonly used to derive precise union types from arrays of string literals via typeof colors[number].

🏏

Cricket analogy: readonly captain: string on a Team interface stops reassigning the captain field at compile time, like a rulebook forbidding mid-innings captaincy changes on paper -- but as const on ['Kohli','Root','Smith'] freezes it into a readonly tuple you can derive a union type from.

Q10. What does this function's return type resolve to? function wrap<T>(value: T) { return { value }; } const result = wrap('hello');

TypeScript infers the generic parameter T as 'string' from the call argument 'hello', so the return type of wrap is inferred as { value: string }, and 'result' has the type { value: string }. This demonstrates contextual generic inference: you never have to write wrap<string>('hello') explicitly because the compiler infers T from the argument's type.

🏏

Cricket analogy: Calling analyze('century') on a generic analyze<T>(stat: T) function, TypeScript infers T as string straight from the argument, the way a scorer instantly knows a milestone type from the term used, no need to write analyze<string>('century') explicitly.

Q11. What is the difference between 'never' and 'void'?

'void' is used for functions that do not return a meaningful value (they may still implicitly return undefined). 'never' represents values that never occur at all — it is the type of a function that always throws an exception or contains an infinite loop, and it is also the type of an unreachable branch, such as the default case of an exhaustively-checked switch. Assigning anything to a 'never'-typed variable outside of 'never' itself is a compile error, which makes 'never' useful for exhaustiveness checks.

🏏

Cricket analogy: void describes an umpire's hand signal function that just communicates a decision without returning data, while never describes a function like declareMatchAbandoned() that always throws -- useful for flagging an impossible "default" outcome in an exhaustive switch.

Q12. How does the TypeScript compiler handle modules that have no type declarations?

When importing a plain JavaScript package without bundled or DefinitelyTyped (@types/package-name) declarations, TypeScript raises 'Could not find a declaration file'. You can resolve this by installing the community types (npm install --save-dev @types/package-name), writing your own .d.ts declaration file, or adding a fallback 'declare module "package-name";' ambient declaration, which types the import as 'any' and silences the error while still compiling.

🏏

Cricket analogy: Importing a plain-JS scoring library with no type info is like fielding a substitute player with no scouting report -- you either request the official scouting file (@types/package), write your own notes (.d.ts), or wave them onto the field untyped (declare module).

3. Quick Reference

  • any = no type safety; unknown = safe, requires narrowing before use.
  • Excess property checks only fire on object literals assigned directly, not via an intermediate variable.
  • interface supports declaration merging; type alias supports unions/intersections/primitives.
  • strict: true bundles strictNullChecks, noImplicitAny, strictFunctionTypes, and more.
  • as const infers readonly literal types instead of widened primitive types.
  • never = unreachable/always-throws; void = no meaningful return value.

4. Key Takeaways

  • TypeScript adds compile-time static types on top of JavaScript and erases them at build time.
  • Prefer unknown over any, and enable strict mode for maximum type safety.
  • Generics preserve type information through reusable functions and classes instead of using any.
  • Interfaces and type aliases overlap but differ in declaration merging and what they can express.
  • Type guards and discriminated unions are the standard pattern for narrowing union types safely.

Practice what you learned

Was this page helpful?

Topics covered

#TypeScript#TypeScriptProgrammingStudyNotes#Programming#CommonTypeScriptInterviewQuestions#Common#Interview#Questions#Frequently#StudyNotes#SkillVeris