Complete TypeScript Interview Questions & Answer Bank
75+ curated TypeScript interview questions covering core type primitives, structural typing, generics, utility types, mapped types, advanced type inference, decorators, and compiler optimization.
Q1: What is TypeScript and what are its core advantages over plain JavaScript?
TypeScript is a strongly typed, open-source programming language developed by Microsoft that builds on JavaScript by adding syntactical type declarations.
Core Advantages
- Static Type Checking: Catches errors at compile time rather than runtime.
- Enhanced IDE Support: Enables intelligent autocompletion, refactoring, and code navigation.
- Downlevel Compilation: Transpiles modern ECMAScript features down to older ES versions (ES5/ES3).
- Explicit Self-Documenting Code: Interfaces and type aliases act as living documentation.
TypeScript is a strict syntactical superset of JavaScript.
All valid JavaScript code is valid TypeScript code.
Q2: What is Structural Typing (Duck Typing) and how does it differ from Nominal Typing?
TypeScript uses a Structural Type System. Types are evaluated solely by their shape or structure (the properties and methods they possess), rather than their explicit declaration name or inheritance chain.
In Nominal Type Systems (like Java or C#), two objects with identical properties are not interchangeable unless they explicitly inherit from the same named class or interface.
interface Point2D { x: number; y: number; }
interface Vector2D { x: number; y: number; }
const logPoint = (p: Point2D) => console.log(`${p.x}, ${p.y}`);
const velocity: Vector2D = { x: 10, y: 20 };
logPoint(velocity); // Valid! Vector2D matches the structure of Point2D.Even though velocity is typed as Vector2D, TypeScript accepts it because its internal structure matches Point2D.
TypeScript checks structure, not explicit declaration names.
If an object has the required fields with matching types, TypeScript considers it compatible.
Q3: What are the primitive types available in TypeScript?
TypeScript supports all native JavaScript primitives alongside type additions:
string: Textual data.number: Floating-point numbers and integers.boolean: True/false values.bigint: Large integers beyond $2^{53} - 1$.symbol: Unique, immutable identifiers.null&undefined: Absence of value or uninitialized state.void: Signals absence of return value from functions.
Primitive types in TypeScript correspond directly to JavaScript's runtime primitive types.
Always use lowercase primitive names (
string,number) rather than wrapper objects (String,Number).
Q4: What is the difference between `any` and `unknown` types?
any disables type checking entirely, turning off compile-time safety. You can access arbitrary properties, call them as functions, or assign them to any target type.
unknown is the type-safe counterpart of any. It represents any value, but TypeScript prevents you from performing arbitrary operations on an unknown variable until you perform explicit type checking or narrowing.
let valueAny: any = "hello";
valueAny.foo.bar(); // Compiles fine, runtime crash!
let valueUnknown: unknown = "hello";
// valueUnknown.trim(); // Error: Object is of type 'unknown'.
if (typeof valueUnknown === "string") {
console.log(valueUnknown.trim()); // Valid! Narrowed safely.
}unknown forces developer verification before property access, preventing accidental runtime exceptions.
Prefer
unknownoveranywhen working with dynamic or unexpected values.unknownrequires explicit narrowing before property access.
Q5: What is the `never` type and how is it used for exhaustive type checking?
The never type represents values that never occur. It represents the return type of functions that never finish (e.g., throwing an error or running an infinite loop).
Because never is a assignable to every type, but no type is assignable to never (except never itself), it is used to perform Exhaustive Type Checking inside switch statements.
type Shape = { kind: 'circle' } | { kind: 'square' };
function getArea(s: Shape): number {
switch (s.kind) {
case 'circle': return Math.PI * 2;
case 'square': return 4;
default:
const _exhaustiveCheck: never = s;
return _exhaustiveCheck;
}
}If a developer adds a new union member to Shape without handling it in the switch statement, TypeScript raises a compile-time error.
neversignals unreachable code paths.Assigning unhandled union cases to
neverguarantees total compile-time switch coverage.
Q6: What is the difference between `type` aliases and `interface` declarations?
Both type and interface define structural contracts, but they differ in capabilities:
Interface vs Type Alias Comparison
Supported by interface | Unsupported by type
Multiple interface declarations with the same name automatically merge properties.
Unsupported by interface | Supported by type
Type aliases can define unions (A | B), primitives, tuples, and mapped types directly.
extends keyword vs Intersection (&)
Interfaces extend other interfaces; types create intersections.
Use
interfacefor public API contracts and object structures that benefit from declaration merging.Use
typefor union types, tuples, primitives, and complex mapped/conditional types.
Q7: What is the difference between Union Types (`|`) and Intersection Types (`&`)?
- Union Type (
A | B): Represents a value that can be either typeAor typeB. You can only access properties common to both types unless narrowed. - Intersection Type (
A & B): Combines multiple type structures into one. The resulting value must satisfy both type contracts simultaneously.
type Admin = { name: string; permissions: string[] };
type User = { name: string; email: string };
// Union: Must be Admin OR User
type Account = Admin | User;
// Intersection: Must have ALL properties from Admin AND User
type SuperAdmin = Admin & User;Intersection types merge structural constraints, requiring all combined properties.
Unions allow one of several types; Intersections merge multiple types into one.
Q8: What are Literal Types and how do `as const` assertions work?
Literal types restrict variables to exact concrete values (strings, numbers, or booleans) rather than wider primitive categories.
A const assertion (as const) instructs TypeScript to infer the narrowest possible literal types for object properties and arrays, turning properties into readonly fields.
// Standard object inference
const config = {
endpoint: "/api",
retries: 3
}; // Type: { endpoint: string; retries: number; }
// const assertion
const constConfig = {
endpoint: "/api",
retries: 3
} as const; // Type: { readonly endpoint: "/api"; readonly retries: 3; }as const prevents property widening and marks array/object members read-only.
Literal types lock values to exact concrete constants.
as constcreates deeply immutable readonly literal data types.
Q9: What are Tuple Types in TypeScript and how do Readonly Tuples work?
A Tuple is a fixed-length array where every element index has an explicitly declared type.
Standard tuples permit mutable array operations like .push(), which can bypass tuple index checks. Wrapping tuples with readonly enforces strict immutability.
type ResponseState = [code: number, message: string];
const state: ResponseState = [200, "OK"];
type ImmutableState = readonly [number, string];
const fixed: ImmutableState = [404, "Not Found"];
// fixed.push("error"); // Error: Property 'push' does not exist on type 'readonly [number, string]'Readonly tuples block array mutation methods like push, pop, or index modification.
Tuples lock array element types to explicit index positions.
Use
readonlyon tuples to block accidental array mutations.
Q10: What are Enums, String Enums, and `const enum` declarations?
Enums allow defining named sets of constants. TypeScript supports Numeric, String, and const enums.
Standard enums generate runtime JavaScript objects. A const enum is completely removed during compilation—its values are directly inlined into call sites, leaving zero JavaScript runtime object footprint.
const enum Direction {
Up = "UP",
Down = "DOWN"
}
const move = Direction.Up;
// Compiled JS output:
// var move = "UP"; // No Enum object generated!const enum inlines literal values directly at compile time, reducing JavaScript bundle size.
Use
const enumto eliminate runtime JavaScript object overhead.String enums offer better readability during debugging than numeric enums.
Q11: What is Type Narrowing and how do build-in Type Guards work?
Type Narrowing is the process where TypeScript refines a broad type (like a union) into a narrower type within a specific code block using logical checks.
Native Guards
typeof: Narrow primitive types (string,number,boolean,symbol).instanceof: Narrow class instances.inoperator: Check if a property key exists on an object.- Truthiness checks (
if (val)): Excludenullorundefined.
Type narrowing leverages standard JavaScript logical conditional checks.
TypeScript inspects execution branches to refine types automatically.
Q12: What are User-Defined Type Guards using custom Type Predicates (`value is T`)?
A User-Defined Type Guard is a function whose return type signature uses a Type Predicate in the form parameterName is Type.
When the function returns true, TypeScript narrow the argument's type in the calling conditional block.
interface Fish { swim: () => void }
interface Bird { fly: () => void }
// Custom Type Guard
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function move(pet: Fish | Bird) {
if (isFish(pet)) {
pet.swim(); // Narrowed safely to Fish
} else {
pet.fly(); // Narrowed safely to Bird
}
}The pet is Fish predicate instructs TypeScript to treat pet as Fish inside the true branch.
Type predicates (
arg is T) allow custom type narrowing logic.Used to encapsulate custom type-validation runtime logic.
Q13: What are Assertion Functions using the `asserts` keyword?
Assertion functions throw an error if a condition check fails. They use the return signature asserts condition or asserts val is T to instruct TypeScript that if the function returns normally without throwing, the asserted type assumption holds true for remaining code execution.
function assertIsString(val: unknown): asserts val is string {
if (typeof val !== "string") {
throw new Error("Not a string!");
}
}
function processInput(input: unknown) {
assertIsString(input);
// input is now safely narrowed to string for all following lines
console.log(input.toUpperCase());
}If assertIsString completes without throwing an error, TypeScript narrow input to string for the remaining scope.
assertsnarrowing stays active across subsequent lines without requiring anifblock.
Q14: What are Discriminated Unions (Tagged Unions)?
A Discriminated Union is a pattern where every type in a union shares a single common literal property (the discriminant tag). TypeScript uses this discriminant property to narrow down exact union members inside switch statements or conditional checks.
interface LoadingState { status: 'loading' }
interface SuccessState { status: 'success'; data: string }
interface ErrorState { status: 'error'; error: Error }
type NetworkState = LoadingState | SuccessState | ErrorState;
function handleState(state: NetworkState) {
switch (state.status) { // status is the discriminant
case 'success':
return state.data; // Safely narrowed to SuccessState
case 'error':
return state.error.message; // Safely narrowed to ErrorState
}
}The shared status literal property allows TypeScript to narrow down the union type.
Use a shared literal property tag across members of a union.
Enables clean, type-safe conditional branching.
Q15: What is the Non-Null Assertion Operator (`!`) and when should it be avoided?
The non-null assertion operator (postfix !) tells the TypeScript compiler to assert that an expression is neither null nor undefined, suppressing strict null checking errors.
It does not emit any runtime protective checks. If the value is null or undefined at runtime, your code will throw an unhandled exception.
The
!operator removesnullandundefinedfrom a type at compile time.It generates no runtime JavaScript protective code—use it with caution.
Q16: How do Optional Chaining (`?.`) and Nullish Coalescing (`??`) work?
- Optional Chaining (
?.): Safely accesses nested object properties or methods. If the left-hand operand isnullorundefined, evaluation stops and returnsundefinedwithout throwing a TypeError. - Nullish Coalescing (
??): A logical operator that returns its right-hand operand only when the left-hand operand evaluates tonullorundefined(unlike||, which triggers on all falsy values like0or"").
?.prevents nested property access runtime errors.??checks explicitly fornullorundefined, ignoring falsy values like0orfalse.
Q17: What are Type Assertions (`as T`) and how do they differ from Type Casting?
Type Assertions instruct the compiler to treat a value as a specific type using the syntax val as T or <T>val.
Type assertions do not perform runtime conversion (casting). They are purely compile-time directives removed during compilation. To convert runtime types (e.g., string to number), you must call JavaScript conversion functions like Number(str).
Type assertions do not change runtime JavaScript data structures.
Use
as unknown as TargetTypefor double assertions when types do not overlap.
Q18: What are Generics and why are they important?
Generics allow you to write reusable, type-safe components that work across multiple data types rather than a single type, while preserving full static type safety.
Type parameters (conventionally written as <T>) act as type variables captured when functions, classes, or interfaces are invoked.
function identity<T>(arg: T): T {
return arg;
}
const str = identity<string>("hello"); // Type: string
const num = identity(42); // Inferred automatically as numberGenerics lock function input types to function output types dynamically.
Generics provide type-safe reusability without resorting to
any.TypeScript infers type parameters automatically based on argument values.
Q19: How do Generic Constraints using the `extends` keyword work?
Generic Constraints restrict the set of types acceptable by a generic parameter using the <T extends Boundary> syntax. This ensures the passed type satisfies specific structural requirements.
interface Lengthwise {
length: number;
}
function logLength<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Guaranteed to exist
return arg;
}
logLength("hello"); // Valid (strings have length)
logLength([1, 2, 3]); // Valid (arrays have length)
// logLength(123); // Error: number doesn't have a 'length' propertyT extends Lengthwise guarantees that any type passed into T possesses a numeric length property.
Use
extendsto enforce required structural properties on generic type arguments.
Q20: How do Generic Parameter Defaults work?
Similar to JavaScript function argument defaults, generic parameter defaults allow specifying fallback types using the <T = DefaultType> syntax when caller type arguments are omitted.
interface ApiResponse<TData = { status: string }> {
data: TData;
statusCode: number;
}
// Uses default type { status: string }
const defaultRes: ApiResponse = { data: { status: "OK" }, statusCode: 200 };
// Overrides default type with custom user structure
const userRes: ApiResponse<{ name: string }> = {
data: { name: "Alice" },
statusCode: 200
};If no generic parameter is explicitly passed, TypeScript defaults to TData = { status: string }.
Generic parameter defaults fall back gracefully when explicit type arguments are omitted.
Q21: What is the `keyof` operator and how is it used?
The keyof operator produces a union of string or numeric literal types representing the key names of an object type.
interface User {
id: number;
name: string;
email: string;
}
type UserKeys = keyof User; // Type: 'id' | 'name' | 'email'
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}K extends keyof T guarantees that the provided key argument exists on the target object type T.
keyof Treturns a union of all property name keys belonging to typeT.
Q22: What is the `typeof` operator in Type Contexts?
In a type expression context, typeof refers to the TypeScript type of a variable or property value, allowing you to infer types directly from runtime variables without writing manual interfaces.
const defaultTheme = {
color: "blue",
fontSize: 14,
isDark: false
};
// Extract type structure from runtime variable
type Theme = typeof defaultTheme;
// Resulting type: { color: string; fontSize: number; isDark: boolean; }typeof converts runtime JavaScript object structures into static TypeScript types.
Use
typeofin type contexts to derive static type contracts directly from runtime JavaScript values.
Q23: How do Indexed Access Types (`T[K]`) work?
An Indexed Access Type looks up specific sub-properties on another type using bracket notation syntax (Type[Key]).
interface Order {
id: string;
customer: {
name: string;
address: { city: string };
};
}
type CustomerType = Order["customer"]; // Type: { name: string; address: { city: string } }
type CityType = Order["customer"]["address"]["city"]; // Type: stringBracket notation pulls property types from complex nested object structures.
Look up property types dynamically from existing structural contracts.
Q24: How do `Partial<T>` and `Required<T>` utility types work?
Partial<T>: Constructs a type with all properties ofTset to optional (?).Required<T>: Constructs a type with all properties ofTset to required (removes optional?flags).
interface Profile {
name: string;
age?: number;
}
type OptionalProfile = Partial<Profile>; // { name?: string; age?: number; }
type MandatoryProfile = Required<Profile>; // { name: string; age: number; }Partial makes all properties optional; Required makes all properties mandatory.
Partial is ideal for update payload signatures (
patch).Required guarantees optional fields are populated.
Q25: How do `Readonly<T>` and `Record<K, T>` utility types work?
Readonly<T>: Sets all properties ofTtoreadonly, preventing property re-assignment.Record<Keys, Type>: Constructs an object type whose property keys are derived fromKeysand whose values are of typeType.
type Page = 'home' | 'about' | 'contact';
interface PageInfo { title: string }
const navPages: Record<Page, PageInfo> = {
home: { title: 'Home' },
about: { title: 'About' },
contact: { title: 'Contact' }
};Record enforces that all listed key members exist in the target mapping dictionary object.
Use
Recordto construct strongly-typed dictionary maps.
Q26: How do `Pick<T, K>` and `Omit<T, K>` utility types work?
Pick<T, Keys>: Constructs a type by picking a specific set of property keys fromT.Omit<T, Keys>: Constructs a type by removing a specific set of property keys fromT.
interface Article {
id: number;
title: string;
content: string;
author: string;
}
type ArticlePreview = Pick<Article, 'id' | 'title'>; // Contains ONLY id & title
type ArticleDraft = Omit<Article, 'id'>; // Contains title, content, authorPick creates a subset with selected keys; Omit creates a subset excluding specified keys.
Pick selects specific keys; Omit excludes specific keys.
Q27: How do `Exclude<T, U>`, `Extract<T, U>`, and `NonNullable<T>` work?
These utility types operate over union types:
Exclude<Union, ExcludedMembers>: Removes matching members from a union.Extract<Union, ExtractedMembers>: Keeps only matching members from a union.NonNullable<T>: Excludesnullandundefinedfrom a union type.
Operate over union types via distributive conditional logic.
Q28: How do `ReturnType<T>` and `Parameters<T>` utility types work?
ReturnType<FunctionType>: Extracts the return type of a function signature.Parameters<FunctionType>: Extracts the parameter types of a function signature as a tuple.
function createTask(title: string, priority: number) {
return { id: Date.now(), title, priority };
}
type TaskReturn = ReturnType<typeof createTask>; // { id: number, title: string, priority: number }
type TaskParams = Parameters<typeof createTask>; // [title: string, priority: number]Infer return and parameter types dynamically using ReturnType and Parameters.
Use
ReturnTypeandParametersto extract function signature types dynamically.
Q29: What are Conditional Types and how does the ternary syntax (`T extends U ? X : Y`) work?
Conditional types select one of two possible types based on a type relationship check, using a syntax similar to conditional ternary expressions:
T extends U ? TrueType : FalseType
type IsString<T> = T extends string ? true : false;
type Test1 = IsString<string>; // true
type Test2 = IsString<number>; // falseIf T is assignable to string, evaluate to true; otherwise evaluate to false.
Conditional types enable dynamic compile-time decision logic.
Q30: What are Distributive Conditional Types and how can distribution be disabled?
When conditional types act on a bare generic type parameter (T), they automatically distribute across union types.
For example, IsString<A | B> evaluates as IsString<A> | IsString<B>.
To disable distribution, wrap the generic type parameter in square brackets: [T] extends [U].
type ToArrayDistributive<T> = T extends any ? T[] : never;
type Distributed = ToArrayDistributive<string | number>; // string[] | number[]
type ToArrayNonDistributive<T> = [T] extends [any] ? T[] : never;
type NonDistributed = ToArrayNonDistributive<string | number>; // (string | number)[]Wrapping T in tuple brackets prevents unions from splitting during evaluation.
Unwrapped type parameters distribute automatically across unions in conditional types.
Wrap type parameters in tuple brackets
[T]to disable distribution.