Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

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
  1. Aany
  2. BunknownCorrect answer
  3. Cobject
  4. Dvoid

Why: unknown is the type-safe counterpart of any.

2What does Partial<User> produce?Asked almost every time
  1. AA readonly User
  2. BUser with all properties required
  3. CUser with all properties optionalCorrect answer
  4. DOnly User's keys

Why: Partial makes every property optional.

3Which can be merged by declaring it twice?Asked almost every time
  1. Atuple
  2. Btype alias
  3. CinterfaceCorrect answer
  4. Denum const

Why: Interfaces support declaration merging.

4Which type gives the props of a native button?Asked almost every time
  1. AHTMLButton
  2. BButtonProps
  3. CReact.Button
  4. DReact.ComponentProps<'button'>Correct answer

Why: Extend it for custom buttons.

5What does T extends { length: number } do?Asked almost every time
  1. ACreates a class
  2. BCopies T
  3. CConstrains T to types with a lengthCorrect answer
  4. DMakes T a string

Why: A generic constraint.

6Which flag types index access as possibly undefined?Asked almost every time
  1. AalwaysStrict
  2. BnoUncheckedIndexedAccessCorrect answer
  3. CstrictNullChecks only
  4. DnoImplicitAny

Why: Safer index signatures.

7What does keyof { a: 1; b: 2 } give?Very often asked
  1. Aobject
  2. B"a" | "b"Correct answer
  3. C1 | 2
  4. Dstring

Why: keyof yields the union of keys.

8Which utility type removes keys from a type?Very often asked
  1. AOmitCorrect answer
  2. BExclude
  3. CExtract
  4. DPick

Why: Omit<T, K> drops properties K.

9What is the type of a function that always throws?Very often asked
  1. Avoid
  2. Bundefined
  3. CneverCorrect answer
  4. Dnull

Why: It never returns normally.

10Which operator checks a value against a type but keeps its inferred type?Very often asked
  1. Ais
  2. Binfer
  3. Cas
  4. DsatisfiesCorrect answer

Why: satisfies validates without widening.

11What does as const do to ['a', 'b']?Very often asked
  1. AMakes it string[]
  2. BFreezes it at runtime
  3. CNothing
  4. DMakes it readonly ['a', 'b']Correct answer

Why: Literal tuple type.

12Which gets the element union of a const array?Very often asked
  1. AArrayType<arr>
  2. Barr[]
  3. C(typeof arr)[number]Correct answer
  4. Dkeyof arr

Why: Indexed access by number.

13Which unwraps a Promise type?Very often asked
  1. AUnwrap<T>
  2. BResolve<T>
  3. CPromise.type<T>
  4. DAwaited<T>Correct answer

Why: Handles nested promises.

14Which adds properties to a library's interface?Very often asked
  1. AEnum merging
  2. BNamespaces only
  3. CModule augmentationCorrect answer
  4. DType casting

Why: declare module 'lib'.

15Function parameters are, under strictFunctionTypes…Very often asked
  1. AIgnored
  2. BContravariantCorrect answer
  3. CCovariant
  4. DInvariant always

Why: Methods remain bivariant.

16What does infer do in a conditional type?Often asked
  1. AImports a type
  2. BCreates an enum
  3. CRuns code
  4. DDeclares a type variable to capture part of a typeCorrect answer

Why: e.g. T extends Promise<infer U> ? U : T.

17Which flag makes null and undefined distinct types?Often asked
  1. AskipLibCheck
  2. BnoImplicitAny
  3. CstrictNullChecksCorrect answer
  4. DesModuleInterop

Why: Without it, null fits every type.

18Record<'a' | 'b', number> is…Often asked
  1. A{ a: number; b: number }Correct answer
  2. Bnumber[]
  3. CMap<string, number>
  4. D'a' | 'b'

Why: Record maps each key to the value type.

19A user-defined type guard has the return type…Often asked
  1. Avalue is TypeCorrect answer
  2. Basserts Type
  3. CType
  4. Dboolean only

Why: The is predicate narrows on true.

20Branded types simulate…Often asked
  1. AEnums
  2. BDecorators
  3. CNominal typingCorrect answer
  4. DRuntime classes

Why: UserId vs. OrderId.

21Which tsconfig keys define path aliases?Often asked
  1. Ainclude and exclude
  2. Blib and target
  3. CbaseUrl and pathsCorrect answer
  4. DrootDir and outDir

Why: Bundlers must resolve them too.

22Which exist at runtime?Often asked
  1. AUtility types
  2. BAbstract classesCorrect answer
  3. CInterfaces
  4. DType aliases

Why: Types are erased.

23What does NoInfer<T> prevent?Often asked
  1. AAny types
  2. BNull values
  3. CInferring T from that argumentCorrect answer
  4. DUsing generics

Why: Added in TypeScript 5.4.

24Which gets a function's parameter types?Often asked
  1. AArgs<fn>
  2. BReturnType<typeof fn>
  3. CInputs<fn>
  4. DParameters<typeof fn>Correct answer

Why: A tuple of parameter types.

25Template literal types can produce…Often asked
  1. ANumbers only
  2. BUnions of string patternsCorrect answer
  3. CRuntime strings
  4. DClasses

Why: e.g. on${string}.

26What does as const do to an object literal?Sometimes asked
  1. ARemoves types
  2. BMakes it mutable
  3. CMakes properties readonly with literal typesCorrect answer
  4. DConverts it to an enum

Why: Values keep their literal types.

27Where do community types for untyped packages come from?Sometimes asked
  1. Anpm audit
  2. Btsconfig paths
  3. Ceslint
  4. D@types packages (DefinitelyTyped)Correct answer

Why: DefinitelyTyped publishes @types/* packages.

28TypeScript type checking happens…Sometimes asked
  1. AOnly in tests
  2. BAt runtime
  3. CAt compile timeCorrect answer
  4. DIn the database

Why: Types are erased in the emitted JavaScript.

29Which tools strip types without type checking?Sometimes asked
  1. APrettier
  2. Besbuild, SWC and BabelCorrect answer
  3. Ctsc only
  4. DESLint

Why: Run tsc --noEmit separately.

30exactOptionalPropertyTypes rejects…Sometimes asked
  1. ANull values
  2. BReadonly arrays
  3. CExplicit undefined for optional propsCorrect answer
  4. DOptional props

Why: Unless undefined is in the type.

Track what you have practised and search every bank in your dashboard.

Start learning