FlexQ

Interview questions

TypeScript interview questions and answers

A TypeScript interview checks whether you use the type system to catch real bugs: narrowing unions, writing generics, modelling states so impossible ones can not be written, and knowing what types do not protect you from at runtime.

For live interviews: the FlexQ interview copilot for Mac or Windows, 30 free live minutes.

Updated 2026-11-23 · 21 questions · junior, mid-level, senior and a coding round · a model answer and what the interviewer is checking for each

The code samples assume strict mode, which most teams turn on. They use features available since TypeScript 4.9 (satisfies); nothing here depends on a newer release.

Jump to: Junior · Mid-level · Senior · Coding round · How to practice · FAQ

Junior TypeScript questions

Junior questions check what TypeScript is for and the everyday tools: annotations, unions and narrowing.

1. What does TypeScript add to JavaScript, and what happens to the types at runtime?

Model answer: TypeScript adds static types that the compiler checks before the code runs, which catches typos, wrong arguments and missing null checks, and powers editor autocomplete and safe refactoring. The types are erased when the code is compiled to JavaScript, so nothing checks them at runtime. A response from an API typed as User is only a promise you made to the compiler. Data from outside the program needs runtime validation.

What the interviewer is checking: That you know types are erased, which separates real understanding from tool usage.

2. What is the difference between interface and type?

Model answer: Both can describe the shape of an object, and in most code either works. An interface can be reopened and merged by declaring it again, and extends other interfaces with extends. A type alias can name anything, including unions, tuples, primitives, and mapped or conditional types, which interfaces can not express. Many teams use interface for object shapes and public APIs and type for everything else; the important thing is one consistent rule.

What the interviewer is checking: Knowing the real differences (merging, unions) instead of a strong opinion.

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

Model answer: any turns type checking off for that value: you can do anything with it, and errors spread silently. unknown also accepts any value, but you must narrow it, with typeof, a type guard or validation, before using it, which makes it the safe type for data you have not checked yet. never is the type with no values: the return type of a function that always throws, and what a union narrows to when every case has been handled.

What the interviewer is checking: Whether you reach for unknown instead of any at boundaries.

4. How does narrowing work for union types?

Model answer: A union such as string | number only allows operations valid for every member. Inside a check, TypeScript narrows the type: after typeof x === 'string' it is a string in that branch. Other narrowing checks are instanceof, the in operator, equality checks such as x !== null, a shared literal property in a discriminated union, and custom type guards that return value is Type. Narrowing follows control flow, so an early return narrows the rest of the function.

What the interviewer is checking: Everyday fluency with the most used feature of the type system.

5. What do ?, ?., ?? and the ! after a value mean?

Model answer: A ? after a property or parameter name makes it optional, so its type includes undefined. a?.b is optional chaining, a JavaScript feature: it returns undefined instead of throwing if a is null or undefined. a ?? b is JavaScript's nullish coalescing: b only when a is null or undefined. A ! after an expression, as in el!.focus(), is a TypeScript-only non-null assertion: it tells the compiler the value is not null without checking, so it moves the risk to runtime.

What the interviewer is checking: Separating JavaScript features from TypeScript ones, and caution with !.

6. What does the strict option turn on, and why does it matter?

Model answer: strict enables a family of checks, among them strictNullChecks, noImplicitAny, strictFunctionTypes, strictPropertyInitialization and useUnknownInCatchVariables. The most valuable is strictNullChecks: without it, null and undefined fit every type, so the most common runtime error goes unchecked. New projects should start strict; older ones can turn the checks on one at a time.

What the interviewer is checking: That you know where the value of TypeScript actually comes from.

Mid-level TypeScript questions

Mid-level questions are about writing types other people use: generics, utility types and modelling state.

7. What are generics? Write a small generic function.

Model answer: A generic is a type parameter: the function works for many types while keeping the link between input and output. Here the return type follows the array's element type, so calling it with numbers gives number | undefined without any annotation at the call site. Constraints such as <T extends { id: string }> limit which types are allowed. Without generics you would write any and lose that link.

function first<T>(items: readonly T[]): T | undefined {
  return items[0];
}

const n = first([1, 2, 3]);   // number | undefined
const s = first(['a', 'b']);  // string | undefined

What the interviewer is checking: Whether you understand generics as preserving information.

8. What is a discriminated union, and how do you make a switch over it exhaustive?

Model answer: It is a union of object types that share a literal property, the discriminant, such as kind. Checking that property narrows to one member, so each branch gets the right fields. For exhaustiveness, assign the value to a variable of type never in the default branch: if someone adds a new member and forgets a case, that line no longer compiles. This is also the cleanest way to model UI states such as loading, error and success.

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'square':
      return shape.size ** 2;
    default: {
      const unreachable: never = shape;
      throw new Error(`Unknown shape: ${JSON.stringify(unreachable)}`);
    }
  }
}

What the interviewer is checking: Modelling with types so that missing cases become compile errors.

9. Explain Partial, Required, Pick, Omit, Record and ReturnType.

Model answer: Partial<T> makes every property optional, which suits update payloads; Required<T> does the opposite. Pick<T, 'a' | 'b'> keeps only those keys and Omit<T, 'a'> removes them. Record<K, V> is an object type with keys K and values V. ReturnType<typeof fn> extracts a function's return type, and Parameters its argument types. They let you derive types from one source instead of copying them.

What the interviewer is checking: Knowing the built-ins well enough to avoid duplicated types.

10. What do keyof and typeof do in a type position?

Model answer: In a type, typeof value gives the type of an existing variable, so you can derive a type from a config object instead of writing it twice. keyof T gives the union of T's property names. Together with an indexed access type, T[K], they let a function accept only valid keys and return the matching value type. In this example, get('retries') returns a number and get('retry') does not compile.

const config = { retries: 3, verbose: false };

type Config = typeof config;   // { retries: number; verbose: boolean }
type ConfigKey = keyof Config; // 'retries' | 'verbose'

function get<K extends ConfigKey>(key: K): Config[K] {
  return config[key];
}

What the interviewer is checking: Deriving types from values, a sign of practical TypeScript experience.

11. What is the difference between as and satisfies?

Model answer: value as Type is an assertion: you overrule the compiler, and it accepts it as long as the types overlap at all, so mistakes slip through. value satisfies Type, added in TypeScript 4.9, checks that the value matches the type but keeps the more precise type the compiler inferred. In this example, a value that is not a string is an error, and routes.usr is still an error because the object keeps its exact keys. A plain annotation : Record<string, string> would allow any key.

const routes = {
  home: '/',
  user: '/users/:id',
} satisfies Record<string, string>;

routes.user; // string
// routes.usr would be a compile error

What the interviewer is checking: Whether you avoid assertions and know the newer, safer tool.

12. How do you type a React component's props and event handlers?

Model answer: Describe props with a type or interface and annotate the function parameter. To accept every native attribute of an element, extend React.ComponentPropsWithoutRef<'button'> (or ComponentPropsWithRef when the component forwards a ref). Events are typed by element: React.ChangeEvent<HTMLInputElement> for an input change, React.MouseEvent<HTMLButtonElement> for a click. For children, use React.ReactNode.

type ButtonProps = React.ComponentPropsWithoutRef<'button'> & {
  variant?: 'primary' | 'ghost';
};

function Button({ variant = 'primary', ...rest }: ButtonProps) {
  return <button className={`btn btn-${variant}`} {...rest} />;
}

What the interviewer is checking: Day-to-day TypeScript in a frontend codebase.

13. Why does an object with extra properties sometimes pass a type check and sometimes fail?

Model answer: TypeScript is structural: a value fits a type if it has the required properties, and extra ones are normally fine. The exception is an object literal written directly where a type is expected: then excess property checking reports unknown properties, because there they are almost always typos. If you first assign the literal to a variable and pass the variable, the extra properties are allowed. That is consistent, not a bug: the check targets fresh literals only.

What the interviewer is checking: Understanding structural typing instead of being surprised by it.

Senior TypeScript questions

Senior questions test advanced types, safety at the boundaries and keeping a large codebase fast to compile.

14. What are conditional types, and what does infer do?

Model answer: A conditional type, T extends U ? X : Y, picks a type based on whether T is assignable to U. Inside the condition, infer declares a type variable that TypeScript fills from the match, which is how you extract a part of a type. When T is a bare type parameter and receives a union, the condition is applied to each member separately (it distributes). Built-ins such as ReturnType and Awaited are written this way.

type ElementType<T> = T extends readonly (infer U)[] ? U : never;

type A = ElementType<string[]>;          // string
type B = ElementType<number[] | boolean>; // number (boolean gives never)

What the interviewer is checking: Whether you can read and write the types that libraries are made of.

15. What are mapped types, and how does key remapping with as work?

Model answer: A mapped type builds a new object type by iterating over keys: { [K in keyof T]: ... }. Modifiers add or remove readonly and ?, which is how Partial and Readonly are built. Since TypeScript 4.1, an as clause renames keys, often with template literal types, and remapping a key to never drops it. This example generates getter names from a type's properties.

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

What the interviewer is checking: Comfort with type-level programming, used with restraint.

16. How do you make data from an API type-safe?

Model answer: A type annotation on await res.json() is an assumption, not a check. Validate at the boundary with a schema library such as Zod, Valibot or a validator generated from an OpenAPI spec, and derive the static type from the same schema so the two can not drift. Invalid data then fails at the edge with a clear error, instead of as undefined deep inside the UI. For internal APIs, generating types from the backend's schema is the next best thing.

import { z } from 'zod';

const User = z.object({ id: z.string(), email: z.string().email() });
type User = z.infer<typeof User>;

const user: User = User.parse(await res.json()); // throws if the shape is wrong

What the interviewer is checking: That you know where the type system ends and act on it.

17. What are branded types, and when are they worth it?

Model answer: Structural typing means a UserId and an OrderId that are both strings are interchangeable, so passing one where the other belongs compiles. A brand adds a phantom property that exists only in the type, so the two become incompatible. Values get the brand through one constructor function, ideally one that validates. They are worth it for IDs, currencies and units, where a mix-up is a real bug.

type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };

const toUserId = (raw: string) => raw as UserId;

function loadUser(id: UserId) { /* ... */ }
loadUser(toUserId('u_123')); // ok
// loadUser('u_123') and loadUser(orderId) are compile errors

What the interviewer is checking: Using types to prevent a class of bugs, with judgment about cost.

18. Why can a callback that accepts Animal be used where one that accepts Dog is expected, but not the other way round?

Model answer: Function parameters are checked contravariantly: a function that can handle any animal can certainly handle a dog, but one that only handles dogs can not safely receive a cat. With strictFunctionTypes, TypeScript enforces this for function types. Methods declared with method shorthand in an interface are still checked bivariantly for compatibility with existing code, which is a known gap. Return types are covariant: returning a Dog where an Animal is expected is fine.

What the interviewer is checking: A precise model of variance, which explains confusing assignability errors.

19. How do you keep type checking fast in a large codebase or monorepo?

Model answer: Measure first with tsc --extendedDiagnostics, and --generateTrace to find slow files and types. Split the code into project references and build with tsc -b, so only changed projects are checked, and turn on incremental. Let a fast transpiler such as esbuild or SWC strip types for development builds, with isolatedModules on so every file can be compiled alone, and run full type checking as a separate CI step. Very large unions and deeply recursive conditional types are the usual hot spots.

What the interviewer is checking: Experience running TypeScript at scale, not just writing it.

TypeScript coding round

TypeScript coding tasks are either a typed utility function or a utility type. Say what the types should ensure before you write them.

20. Write a type-safe groupBy function.

Model answer: Two type parameters: T for the items and K for the key, both inferred from the call. Returning a Map keeps any key type and avoids pretending that every possible key exists in an object. Modern runtimes now ship Map.groupBy and Object.groupBy (ES2024); mention them, and write your own when the target environment is older.

function groupBy<T, K>(items: readonly T[], getKey: (item: T) => K): Map<K, T[]> {
  const groups = new Map<K, T[]>();
  for (const item of items) {
    const key = getKey(item);
    const group = groups.get(key);
    if (group) group.push(item);
    else groups.set(key, [item]);
  }
  return groups;
}

const byRole = groupBy(users, (u) => u.role); // Map<string, User[]>

What the interviewer is checking: Inference-friendly generics and an honest return type.

21. Write a DeepReadonly<T> utility type.

Model answer: Map over every key, add readonly, and recurse into the property types. Leave functions as they are, because mapping over a function type would destroy its call signature. Mapped types applied to arrays and tuples produce readonly arrays and tuples, so this handles nested arrays too. Mention the limits: it marks types only and does nothing at runtime, where Object.freeze would be needed.

type DeepReadonly<T> = T extends (...args: any[]) => unknown
  ? T
  : T extends object
    ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
    : T;

type State = DeepReadonly<{ user: { tags: string[] } }>;
// state.user.tags.push('x') is now a compile error

What the interviewer is checking: Recursive types, edge cases (functions, arrays) and the runtime caveat.

How to practice

Paste each code sample into the TypeScript Playground, break it on purpose and read the error message out loud, because explaining a type error is part of most TypeScript rounds. Rehearse out loud with the free voice mock interviewer at interview.flexq.app: paste the job description, add your résumé if you like, and answer by voice (typing works too). It follows up where an answer is thin and ends with a scored report that quotes your answers back. Three mock interviews are free with an email sign-up, no card.

During the real interview, the FlexQ interview copilot can show short cues on the interviewer's questions, grounded in your résumé and the job post, and you answer in your own words. Follow the rules of the company you're interviewing with.


Practice a free mock interview

Paste a TypeScript or frontend job description and the mock interviewer asks questions like these and follows up on your reasoning. Three mock interviews are free with an email sign-up, no card.

For live interviews: the FlexQ interview copilot for Mac or Windows, 30 free live minutes.

On the real call

FlexQ also has a live copilot for macOS and Windows. Add your résumé and the job description, and when a question like these lands it shows a short cue from your own experience, so you answer in your own words. Your first 30 live minutes are free. Get FlexQ.

FAQ

What TypeScript topics come up most in interviews?

Narrowing and union types, generics, interface versus type, any versus unknown, utility types and typing React components. Senior loops add conditional and mapped types and runtime validation.

Do I need to know advanced types for a frontend job?

You need to read them and write simple ones. Most interviews care more that you model state well and avoid any than that you can write type-level puzzles.

Is TypeScript asked separately from JavaScript?

Often it is part of a JavaScript or React round. Since types disappear at runtime, the JavaScript questions still matter.

How do I explain a TypeScript migration in an interview?

Describe it as incremental: allow JavaScript files, type new code, convert from shared utilities outward and tighten checks step by step. The frontend developer questions include a sample answer.

How should I practice TypeScript for an interview?

Write the examples on this page in the TypeScript Playground, then change them until they break and explain each error out loud. Add one typed utility a day, such as groupBy or pick.

Related

Frontend topics: React · JavaScript · Webpack, Vite and tooling · Frontend system design · Frontend developer

More: Software engineer questions · System design interview questions · "Tell me about yourself" · Practice out loud · All interview questions