Interview questions with answers
TypeScript interview questions and answers
Types vs. interfaces, generics, narrowing, utility and mapped types. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1type vs. interface: when do you use each?Asked almost every time
Both describe object shapes. Interfaces can be reopened and merged (declaration merging) and extended with extends, which suits public object contracts and library types. Type aliases can name anything: unions, intersections, tuples, primitives, mapped and conditional types. Many teams use interfaces for objects and types for everything else; consistency matters more than the choice.
2What are generics and why use them?Asked almost every time
Generics are type parameters that let one function, class or type work with many types while keeping them connected, such as function first<T>(items: T[]): T | undefined. Constraints (<T extends { id: string }>) limit what is accepted. They give reuse without losing type safety, unlike any.
3any vs. unknown vs. never?Asked almost every time
any switches off type checking for a value; it spreads unsafety. unknown accepts anything but forces you to narrow it (typeof, instanceof, a type guard or a schema) before use, so it is the safe choice for untrusted data. never is the type with no values: functions that never return, and exhaustive checks where all cases are handled.
4How does type narrowing work?Asked almost every time
TypeScript refines a union type within a branch based on checks: typeof, instanceof, in, equality, truthiness, and discriminant properties (if (shape.kind === 'circle')). Custom type guards (x is Cat) and assertion functions extend it. Narrowing is what makes unions practical.
5How do you type a React component's props in TypeScript?Asked almost every time
Declare a props type or interface and annotate the parameter: function Button({ label, onClick }: { label: string; onClick: () => void }). Use React.ComponentProps<'button'> to extend native element props, children: React.ReactNode for content, and generics for components like typed lists.
6What are template literal types?Asked almost every time
Types built from string patterns, such as on${Capitalize<Name>}, which turns a Name union like 'click' | 'focus' into 'onClick' | 'onFocus'. Combined with unions they generate many string types, and with infer they can parse strings at the type level, for example extracting route params from a path.
7How do you make a function work with several input types safely?Asked almost every time
Use overloads for a fixed set of signatures, generics with constraints (<T extends { id: string }>) when the output depends on the input type, or unions with narrowing inside. Prefer generics over overloads when one signature can express the relationship.
8Explain discriminated unions with an example.Very often asked
A union of object types that share a literal 'tag' property, such as type Result = { status: 'ok'; data: User } | { status: 'error'; error: string }. Checking status narrows to one member, and a switch with a never default makes the compiler flag any unhandled case when a new member is added.
9Name useful utility types and what they do.Very often asked
Partial<T> (all optional), Required<T>, Readonly<T>, Pick<T, K>, Omit<T, K>, Record<K, V>, ReturnType<F>, Parameters<F>, Awaited<T>, NonNullable<T>, Exclude and Extract on unions. They derive new types from existing ones instead of repeating definitions.
10What are mapped and conditional types?Very often asked
Mapped types build a type by transforming each key: { [K in keyof T]?: T[K] } is Partial. Conditional types choose a type by a test: T extends string ? 'text' : 'other', distributing over unions, and infer extracts parts such as a function's return type. Together they power most utility types.
11What does strict mode turn on and why use it?Very often asked
strict: true enables strictNullChecks (null and undefined must be handled), noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, useUnknownInCatchVariables and more. It catches far more bugs; new projects should always use it.
12How do you type data coming from an API?Very often asked
Types disappear at runtime, so annotate the response as unknown and validate it with a schema library such as Zod or Valibot, then infer the TypeScript type from the schema (z.infer<typeof User>). One source of truth, checked at the boundary.
13What does extends mean in generics?Very often asked
It constrains a type parameter: function getLength<T extends { length: number }>(x: T) accepts anything with a length. In conditional types, T extends U ? X : Y checks assignability and distributes over unions.
14What are index signatures and when are they risky?Very often asked
{ [key: string]: number } describes objects with any string keys. Accessing a missing key returns undefined at runtime but is typed as number unless noUncheckedIndexedAccess is enabled. Prefer Record with known keys or a Map where possible.
15What is declaration merging and module augmentation?Very often asked
Interfaces with the same name merge their members. Module augmentation (declare module 'lib' { interface Options { extra: string } }) adds types to a library's interfaces, for example registering a router or adding properties to Express's Request.
16What is the difference between readonly and as const?Very often asked
readonly marks properties or arrays as not writable in types. as const makes a literal deeply readonly and narrows its values to literal types ('admin' instead of string), useful for config objects and creating unions from arrays.
17How do you derive types from values?Very often asked
Use typeof on a value to get its type, keyof typeof obj for its keys, (typeof arr)[number] for an array element union, ReturnType<typeof fn> and Parameters<typeof fn>. Single sources of truth reduce duplicated definitions.
18How do you type async functions and promises?Very often asked
An async function returns Promise<T>; annotate as async function load(): Promise<User>. Use Awaited<T> to unwrap nested promise types, and type Promise.all results by passing a tuple.
19What is variance in TypeScript?Very often asked
How subtyping of components relates to subtyping of composite types. Return types are covariant; function parameters are contravariant under strictFunctionTypes (method parameters stay bivariant). Explicit in and out modifiers on type parameters can document and enforce it.
20What does satisfies do?Often asked
value satisfies Type checks that a value conforms to a type without widening the value's own inferred type. You keep precise literal types (for autocompletion and narrowing) while still getting an error if the shape is wrong, unlike a type annotation which replaces the inferred type.
21What is the difference between keyof and typeof in types?Often asked
typeof value in a type position gives the type of a JavaScript value, such as a config object. keyof T gives the union of T's keys. Together, keyof typeof config lists the keys of an object value.
22What are declaration files (.d.ts)?Often asked
Files containing only type declarations for JavaScript code, so TypeScript knows the shapes of untyped libraries or globals. Packages ship them, or they come from DefinitelyTyped (@types/...). declare module adds types for modules without them.
23What are enums, and why do some teams avoid them?Often asked
Enums define named constants and emit JavaScript objects at runtime; numeric enums allow any number and have reverse mappings. Teams often prefer union of string literals or as const objects, which add no runtime code and work with type-stripping tools such as Node's built-in TypeScript support.
24What are abstract classes vs. interfaces?Often asked
Interfaces describe shape only and disappear at runtime. Abstract classes can contain implemented methods and fields plus abstract members subclasses must implement, and exist at runtime. Use interfaces for contracts and abstract classes for shared behaviour.
25What are branded types?Often asked
A way to simulate nominal types: type UserId = string & { readonly __brand: 'UserId' }. Values must be created through a function that validates and casts, so you cannot accidentally pass an OrderId where a UserId is expected.
26How do you configure path aliases?Often asked
Set baseUrl and paths (for example '@/*': ['./src/*']) in tsconfig, and make sure the bundler or runtime resolves them too (Next.js and Vite read tsconfig paths; Node needs imports in package.json or a loader).
27What does exactOptionalPropertyTypes do?Often asked
It distinguishes a missing optional property from one explicitly set to undefined, so { name?: string } no longer accepts { name: undefined } unless the type includes undefined.
28What is the NoInfer utility type?Often asked
Added in TypeScript 5.4, it stops a type parameter from being inferred from a particular argument, so another argument decides the type, as in function pick<T extends string>(options: T[], fallback: NoInfer<T>).
29How does structural typing differ from nominal typing?Sometimes asked
TypeScript compares types by their shape: any object with the required properties fits, whatever its declared name. Nominal systems (Java, C#) require the declared type. Branded types (string & { __brand: 'UserId' }) simulate nominal typing when needed.
30How does TypeScript compile and what is isolatedModules?Sometimes asked
tsc type-checks and emits JavaScript, but many tools (esbuild, SWC, Babel) strip types per file without type checking. isolatedModules warns about code that needs whole-program information to compile, such as re-exporting types without export type.
Objective questions 30
1Which type forces you to narrow before use?Asked almost every time
Why: unknown is the type-safe counterpart of any.
2What does Partial<User> produce?Asked almost every time
Why: Partial makes every property optional.
3Which can be merged by declaring it twice?Asked almost every time
Why: Interfaces support declaration merging.
4Which type gives the props of a native button?Asked almost every time
Why: Extend it for custom buttons.
5What does T extends { length: number } do?Asked almost every time
Why: A generic constraint.
6Which flag types index access as possibly undefined?Asked almost every time
Why: Safer index signatures.
7What does keyof { a: 1; b: 2 } give?Very often asked
Why: keyof yields the union of keys.
8Which utility type removes keys from a type?Very often asked
Why: Omit<T, K> drops properties K.
9What is the type of a function that always throws?Very often asked
Why: It never returns normally.
10Which operator checks a value against a type but keeps its inferred type?Very often asked
Why: satisfies validates without widening.
11What does as const do to ['a', 'b']?Very often asked
Why: Literal tuple type.
12Which gets the element union of a const array?Very often asked
Why: Indexed access by number.
13Which unwraps a Promise type?Very often asked
Why: Handles nested promises.
14Which adds properties to a library's interface?Very often asked
Why: declare module 'lib'.
15Function parameters are, under strictFunctionTypes…Very often asked
Why: Methods remain bivariant.
16What does infer do in a conditional type?Often asked
Why: e.g. T extends Promise<infer U> ? U : T.
17Which flag makes null and undefined distinct types?Often asked
Why: Without it, null fits every type.
18Record<'a' | 'b', number> is…Often asked
Why: Record maps each key to the value type.
19A user-defined type guard has the return type…Often asked
Why: The is predicate narrows on true.
20Branded types simulate…Often asked
Why: UserId vs. OrderId.
21Which tsconfig keys define path aliases?Often asked
Why: Bundlers must resolve them too.
22Which exist at runtime?Often asked
Why: Types are erased.
23What does NoInfer<T> prevent?Often asked
Why: Added in TypeScript 5.4.
24Which gets a function's parameter types?Often asked
Why: A tuple of parameter types.
25Template literal types can produce…Often asked
Why: e.g. on${string}.
26What does as const do to an object literal?Sometimes asked
Why: Values keep their literal types.
27Where do community types for untyped packages come from?Sometimes asked
Why: DefinitelyTyped publishes @types/* packages.
28TypeScript type checking happens…Sometimes asked
Why: Types are erased in the emitted JavaScript.
29Which tools strip types without type checking?Sometimes asked
Why: Run tsc --noEmit separately.
30exactOptionalPropertyTypes rejects…Sometimes asked
Why: Unless undefined is in the type.
Track what you have practised and search every bank in your dashboard.
Start learning