TypeScript Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. What is TypeScript?

    Correct answer: A superset of JavaScript with static typing that compiles to JS

    Any valid JS is almost always valid TS. Types are checked at compile time and then erased: plain JavaScript runs at runtime, and there are no type checks there. That's why external data (APIs, forms) is still validated at runtime - e.g. with Zod.

  2. 2. Does TypeScript check types while the program is running?

    Correct answer: No: types are erased at compile time; plain JS runs at runtime

    TypeScript is a development-time tool. If an API returns null instead of an object, types won't save you. For runtime checks, use typeof/instanceof and schema libraries (Zod, Valibot), from which you can also infer TS types.

  3. 3. How does unknown differ from any?

    Correct answer: You can't do anything with unknown without narrowing, while any disables checks

    any turns typing off and "infects" everything it touches. unknown is the safe counterpart: the value can be anything, but you can use it only after a check (typeof x === 'string'). For data from JSON.parse and catch (e), unknown is the right choice.

  4. 4. What does the never type mean?

    Correct answer: The type of a value that can't exist: the function never returns control

    never is the empty type. It's returned by functions that always throw or loop forever. It also appears when a union is fully narrowed - exhaustive switch checks are built on this. void means the function finishes but its result isn't used.

  5. 5. What type does TypeScript infer for let x = 5;?

    Correct answer: number

    Type inference: for let, the literal widens to number because the variable can be reassigned. For const x = 5, the type is the literal 5. Explicit annotations are needed where inference is impossible or imprecise - e.g. in function parameters.

  6. 6. What's the difference between interface and type for describing an object?

    Correct answer: Both work; interface can be extended by merging, while type can express unions and more

    For objects they're almost interchangeable. Differences: interfaces with the same name merge (declaration merging) and are extended with extends. Type aliases describe unions, tuples, primitives, conditional and mapped types. Many teams use interface for objects and type for everything else.

  7. 7. How do you declare an optional object property?

    Correct answer: { name?: string }

    A ? after the name makes the property optional: its type is string | undefined, and the key itself may be missing. With the exactOptionalPropertyTypes flag, explicitly assigning undefined is distinguished from a missing key.

  8. 8. What does the readonly modifier do in { readonly id: number }?

    Correct answer: Forbids reassigning the property at the type level; nothing changes at runtime

    readonly is just a compiler check: obj.id = 2 causes an error. It's shallow - nested objects can be changed. At runtime the object is ordinary. For arrays there's readonly string[] / ReadonlyArray<string>, and deep freezing is done with as const or Object.freeze.

  9. 9. What does the type string | number mean?

    Correct answer: The value can be a string or a number (a union)

    A union type allows any of its members. Until the type is narrowed, only operations common to all members are available. An intersection is written with & and requires matching all types at once (A & B).

  10. 10. What does the intersection type Admin = User & { role: 'admin' } give you?

    Correct answer: A type with all the properties of User plus role: 'admin'

    An intersection combines requirements: the value must satisfy both types. It's a way to compose types, similar to interface Admin extends User. Conflicting properties produce never for that property.

  11. 11. What is the literal type 'left' | 'right'?

    Correct answer: Only the strings 'left' or 'right'

    Literal types narrow a value down to specific constants. A union of literals is a common alternative to enums: type Direction = 'left' | 'right'. The compiler catches the typo 'lft', and the IDE suggests the options.

  12. 12. How do you type a function that takes a string and returns a number?

    Correct answer: (s: string) => number

    In a function type, parameter names are required: (s: string) => number. (string) => number means a parameter named string of type any. A function declaration: function len(s: string): number { ... }.

  13. 13. How do you declare an optional function parameter?

    Correct answer: function greet(name?: string)

    ? makes the parameter optional; its type is string | undefined. The alternative is a default value: greet(name = 'Guest'), in which case the type is inferred as string. Optional parameters must come after required ones.

  14. 14. What is a tuple in TypeScript?

    Correct answer: A fixed-length array with a known type for each element

    type Point = [number, number] - exactly two numbers. Tuples are handy for returning several values, as in useState: [value, setter]. Elements can be named ([x: number, y: number]) and made optional ([string, number?]).

  15. 15. How do you type an array of strings?

    Correct answer: string[] or Array<string>

    string[] and Array<string> are equivalent. [string] is a one-element tuple. For read-only arrays use readonly string[].

  16. 16. What is a generic?

    Correct answer: A type parameter that keeps the link between types in reusable code

    function first<T>(arr: T[]): T | undefined - the result type is linked to the input array's type: first([1, 2]) returns number | undefined. With any, that link is lost. Generics are used in Array<T>, Promise<T>, useState<T>.

  17. 17. What does the utility type Partial<User> do?

    Correct answer: Makes all properties of User optional

    Partial<T> adds ? to every property - handy for update objects: update(id, patch: Partial<User>). Selecting a subset is Pick, read-only is Readonly, all required is Required.

  18. 18. How do Pick<User, 'id' | 'name'> and Omit<User, 'password'> differ?

    Correct answer: Pick keeps the listed properties, Omit keeps everything except them

    Both create a new type from an existing one. Pick is an allowlist of keys, Omit a denylist. For example, Omit<User, 'password'> is a type for an API response without secret fields.

  19. 19. What does Record<string, number> describe?

    Correct answer: An object whose keys are strings and values are numbers

    Record<K, V> is an object with keys K and values V. With union keys it requires all of them: Record<'en' | 'uk', string>. It isn't a Map: Map is a separate data structure with get/set methods.

  20. 20. What does keyof { id: number; name: string } return?

    Correct answer: 'id' | 'name'

    keyof returns a union of a type's keys. Value types are obtained via indexed access: T['id'] or T[keyof T]. keyof doesn't exist at runtime - use Object.keys for an array of keys.

  21. 21. What does typeof do in a type position: type Config = typeof config?

    Correct answer: Takes the compiler-inferred type of the config variable

    In expressions, typeof is the JS operator that returns a string. In a type position, it's a TypeScript operator that extracts a value's type. Handy for avoiding duplication: const routes = {...} as const; type Routes = typeof routes.

  22. 22. What's wrong with function greet({ name: string }) {}?

    Correct answer: It renames name to a variable string, the type isn't set

    In destructuring, a colon means renaming, not a type: the code creates a variable string, and the parameter stays without a type (under strict it's an implicit any error). The type goes after the whole pattern: function greet({ name }: { name: string }) or via type Params = { name: string }.

  23. 23. What is the type of e.target in input.addEventListener('input', (e) => ...)?

    Correct answer: EventTarget | null - it has no value

    e is inferred as Event, and its target is a general EventTarget | null: the event may come from a nested element. To read value, narrow it with if (e.target instanceof HTMLInputElement) or use the input variable itself, whose type is already known.

  24. 24. What type does const cache = new Map() get without type arguments?

    Correct answer: Map<any, any> - better write new Map<string, User>()

    With no arguments there is nothing to infer from, so K and V become any and every get/set goes unchecked. Pass the types explicitly, new Map<string, User>(), or initial entries: new Map([['a', 1]]) gives Map<string, number>.

  25. 25. What does the type assertion value as string do?

    Correct answer: Tells the compiler to treat the value as a string, with no runtime check

    as is a hint to the compiler, not a conversion: if it's actually a number, the error shows up later. Use it when you know more than the compiler (e.g. the element type from querySelector), and prefer narrowing via checks.

  26. 26. What does the ! operator do in user!.name?

    Correct answer: Asserts the value isn't null/undefined, with no runtime check

    A non-null assertion removes null | undefined from the type. If the value is null after all, you get a runtime error. Safer options are an explicit check or user?.name (optional chaining, returns undefined).

  27. 27. What does the strict flag in tsconfig.json enable?

    Correct answer: A set of strict checks: strictNullChecks, noImplicitAny and others

    strict: true enables a family of flags: strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, useUnknownInCatchVariables and others. New projects should start with strict. It doesn't forbid explicit any - there are linter rules for that.

  28. 28. What does strictNullChecks give you?

    Correct answer: null and undefined become separate types that must be handled explicitly

    Without the flag, null can be assigned to anything, and "cannot read property of null" errors aren't caught. With it, string doesn't include null: you write string | null and check the value before use. It's one of the most useful flags.

  29. 29. How do you narrow string | number to string inside a condition?

    Correct answer: if (typeof value === 'string') { ... }

    TypeScript analyzes control flow: after a typeof check, the type inside the branch is narrowed to string, and in else to number. instanceof String checks for a wrapper object, not a primitive. The x is T syntax is used in the signature of type guard functions.

  30. 30. How does enum Color { Red, Green } differ from type Color = 'red' | 'green'?

    Correct answer: An enum creates an object at runtime; a literal union exists only in types

    A regular enum compiles to a JS object (a numeric one with reverse mapping). A string union adds nothing to the bundle and is compatible with JSON and APIs. Many teams prefer unions or an as const object. Also, enums are incompatible with erasableSyntaxOnly mode.

  31. 31. What does as const do in const roles = ['admin', 'user'] as const?

    Correct answer: Makes the array a readonly tuple with the literal types 'admin' and 'user'

    Without as const, the type is string[]. With it, it's readonly ['admin', 'user'], and you can derive a union: type Role = typeof roles[number] → 'admin' | 'user'. The object isn't frozen at runtime.

  32. 32. What is structural typing in TypeScript?

    Correct answer: Type compatibility is determined by shape (the set of properties), not by name

    If an object has all the properties a type requires, it fits - even if its type has a different name (duck typing). That's why Point2D and Vector2D with the same fields are interchangeable. Nominal behavior can be emulated with branded types.

  33. 33. What is a .d.ts file?

    Correct answer: A declaration file: types for existing JS, no implementation

    Declarations let you use JS libraries with types. They're written by hand, generated by the compiler (declaration: true) or installed from DefinitelyTyped. A .d.ts file contains no executable code.

  34. 34. Why install packages like @types/lodash?

    Correct answer: To get types for a library written in JS without built-in declarations

    @types/* packages are published from the DefinitelyTyped repository and contain only .d.ts files. Many modern libraries ship their own types - then @types isn't needed. They're usually installed as devDependencies.

  35. 35. What does tsc compile a TypeScript file into?

    Correct answer: JavaScript with the type annotations removed

    The compiler checks types and outputs JS for the specified target. In modern projects, building is often done by esbuild, SWC or Babel (which only strip types), and tsc --noEmit is run separately for checking.

  36. 36. What is the type of e in catch (e) with strict enabled?

    Correct answer: unknown

    With the useUnknownInCatchVariables flag (part of strict), e is unknown, since anything can be thrown, not just an Error. Check before use: if (e instanceof Error) console.log(e.message).

  37. 37. What does the return type void mean?

    Correct answer: The function returns nothing useful; the result isn't used

    void is used for functions without a return value. Caveat: the callback type () => void allows passing a function that returns something (the result is ignored) - that's why arr.forEach(x => list.push(x)) compiles. A function that never finishes has the type never.

  38. 38. How do you describe an object with arbitrary string keys and number values using an index signature?

    Correct answer: { [key: string]: number }

    An index signature describes a "dictionary". The equivalent is Record<string, number>. With the noUncheckedIndexedAccess flag, obj[key] returns number | undefined, which better reflects reality.

  39. 39. How do you extend an interface?

    Correct answer: interface Admin extends User { role: string }

    An interface is extended with extends (from several at once: extends A, B). implements is used by classes to guarantee they match an interface. For type aliases, the counterpart is an intersection User & { role: string }.

  40. 40. What does implements do in a class?

    Correct answer: Checks that the class matches the interface; it doesn't inherit anything

    class Cat implements Animal - the compiler checks that the class has all the members of Animal. You have to write the implementation yourself, unlike extends for classes. Interfaces don't exist at runtime.

  41. 41. How does private in TypeScript differ from #field in JavaScript?

    Correct answer: private is only a compiler check, #field is privacy at runtime

    After compilation, a private field is an ordinary property that can be read via obj['field']. #field private fields are supported by the JS engine and can't be accessed from outside the class at all. The public, protected and private modifiers are TypeScript tools.

  42. 42. How do you type an async function that returns a user?

    Correct answer: async function getUser(): Promise<User>

    An async function always returns a promise, so the result type is Promise<User>. The annotation User causes an error. You can extract the promise's value type with Awaited<ReturnType<typeof getUser>>.

  43. 43. What does TypeScript do with const el = document.getElementById('app')?

    Correct answer: Infers HTMLElement | null and requires a null check

    The element may not exist, so the type includes null. For a specific type, use querySelector<HTMLInputElement>('#email') or an instanceof HTMLInputElement check. DOM types are part of the standard library (lib: ['dom']).

  44. 44. What is a union with a common discriminant field?

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

    Correct answer: A discriminated union: TS narrows it by kind

    The check if (shape.kind === 'circle') narrows the type, and shape.radius is available inside. It's the main way to model states: { status: 'loading' } | { status: 'success'; data } | { status: 'error'; error }.

  45. 45. How do you get the return type of the createStore function?

    Correct answer: ReturnType<typeof createStore>

    ReturnType takes a function type, so typeof is needed. Similarly, Parameters<typeof fn> gives a tuple of parameters. This way types are derived from the implementation instead of being duplicated.

  46. 46. What happens when you pass an object literal with an extra property?

    type User = { name: string };
    const u: User = { name: 'Ann', age: 30 };

    Correct answer: An error: literals are subject to excess property checks

    The excess property check applies only to fresh object literals - it's protection against typos. If you first put the object into a variable and then assign it, there's no error (structural compatibility). The compiler doesn't remove anything.

  47. 47. What is tsconfig.json?

    Correct answer: A file with compiler settings and the list of project files

    In compilerOptions you set target, module, strict, paths and so on, while include/exclude define which files belong to the project. Dependencies are described by package.json, and types by .d.ts files. Configs can be inherited via extends.

  48. 48. How do you gradually migrate a JS project to TypeScript?

    Correct answer: Enable allowJs, rename files one by one and tighten the checks

    allowJs lets you mix JS and TS, while checkJs and JSDoc give you types without renaming. Start with leaf modules and utilities, then tighten the strict flags. A full rewrite is risky and halts development.

  49. 49. How does Required<T> differ from Partial<T>?

    Correct answer: Required makes all properties required, Partial makes them optional

    They're opposites: Required removes the ? modifier, Partial adds it. readonly is handled by Readonly<T>. All these utilities are mapped types that you can write yourself.

  50. 50. How do you specify that a function accepts any number of numbers?

    Correct answer: function sum(...nums: number[])

    A rest parameter collects the arguments into an array; its type is an array or a tuple. Call it as sum(1, 2, 3) or sum(...arr).

  51. 51. What does the noImplicitAny option report?

    function greet(name) {
      return 'Hi ' + name;
    }

    Correct answer: Values whose type silently falls back to any

    Here name would be any. The flag is part of strict. Writing any explicitly is still allowed, but it's a visible decision.

  52. 52. How does (string | number)[] differ from string[] | number[]?

    Correct answer: The first may mix both; the second holds only one type

    Parentheses matter: string | number[] would mean "a string or an array of numbers".

  53. 53. What type does const direction = 'left'; get?

    Correct answer: 'left'

    A const can't be reassigned, so TypeScript keeps the literal. With let direction = 'left' it widens to string.

  54. 54. What is the type of users.find((u) => u.id === id) if users: User[]?

    Correct answer: User | undefined

    find may not find anything, so you must handle undefined before using the result.

  55. 55. Why can typeof value === 'object' be a trap when narrowing?

    Correct answer: It's also true for null and arrays

    Combine it with value !== null, or use Array.isArray for arrays. TypeScript reflects this by keeping null in the narrowed type.

  56. 56. What does if (count) miss when count: number | undefined?

    Correct answer: It also excludes 0, a possibly valid value

    Truthiness narrowing treats 0, '' and NaN as false. Use count !== undefined when zero is meaningful.

  57. 57. How does instanceof help with types?

    if (err instanceof HttpError) {
      console.log(err.status);
    }

    Correct answer: It narrows the value to the class type

    instanceof checks the prototype chain at runtime, so it works with classes, not with interfaces or type aliases (they don't exist at runtime).

  58. 58. Why can't you check if (data is User) at runtime?

    Correct answer: Types are erased at compile time; you need runtime code

    TypeScript only checks code at compile time. Data from APIs, localStorage or forms must be validated by real code.

  59. 59. What does Readonly<User> do?

    Correct answer: Makes all properties of User read-only (shallowly)

    Nested objects remain mutable. At runtime nothing changes; use Object.freeze if you need runtime protection.

  60. 60. What does Record<'draft' | 'published', number> require?

    Correct answer: Both keys present, each holding a number

    With a union of literal keys, Record guarantees that no case is forgotten - adding a new status shows errors where it's missing.

  61. 61. What type does const items = []; get with strict enabled?

    Correct answer: An evolving any[], typed by what you push

    Explicit annotation documents intent and prevents surprises when the array is returned or passed elsewhere.

  62. 62. How do you call a generic function with an explicit type argument?

    const value = parse<User>(json);

    Correct answer: Pass the type in angle brackets after the name

    Usually TypeScript infers type arguments from the values. Explicit arguments help when there is nothing to infer from.

  63. 63. How do you write a reusable type for an event handler function?

    type Handler = (event: MouseEvent) => void;

    Correct answer: With a type alias for a function type

    The same can be written as an interface with a call signature, but a type alias is shorter for plain functions.

  64. 64. Why can [1, 2].forEach((n) => console.log(n)) pass a callback with one parameter when forEach passes three?

    Correct answer: A function with fewer parameters is assignable; extra arguments are ignored

    This mirrors common JavaScript practice. The opposite (a callback requiring more parameters than provided) is an error.

  65. 65. What's the result type of user?.address?.city if city: string?

    Correct answer: string | undefined

    Optional chaining stops at the first null/undefined and returns undefined, so the result type includes it.

  66. 66. What is the type of const port = env.PORT ?? 3000 if env.PORT: string | undefined?

    Correct answer: string | number

    ?? removes undefined/null from the left side and adds the type of the right side. Convert with Number(...) if you need a number.

  67. 67. What type does await (await fetch(url)).json() have?

    Correct answer: any - you should annotate or validate the result

    Response.json() returns Promise<any>. Assign it to a typed variable or, better, parse it with a schema to catch API changes.

  68. 68. What does document.createElement('canvas') return in TypeScript?

    Correct answer: HTMLCanvasElement - the type follows the tag name

    The DOM types have an overload keyed by HTMLElementTagNameMap: 'canvas' gives HTMLCanvasElement with getContext, 'input' gives HTMLInputElement. An unknown tag name returns plain HTMLElement. Unlike querySelector, createElement never returns null.

  69. 69. Are Array<string> and string[] different types?

    Correct answer: No - two syntaxes for the same type

    Teams usually pick one style for consistency. For read-only arrays the equivalents are ReadonlyArray<string> and readonly string[].

  70. 70. How do you check types in CI when a bundler (Vite, esbuild) already compiles TS without type checking?

    Correct answer: Run tsc --noEmit as a separate step

    Fast bundlers only strip types. A separate tsc run (or vue-tsc for Vue) catches type errors without producing files.

  71. 71. How does an optional property name?: string differ from name: string | undefined?

    Correct answer: ? allows omitting the property; | undefined doesn't

    The difference matters when creating objects: {} is valid for the first type but not for the second.

  72. 72. How do you describe an object with a method in a type?

    interface Logger {
      log(message: string): void;
      level: 'info' | 'debug';
    }

    Correct answer: Method syntax: log(message: string): void

    Both method and property syntax work. With strictFunctionTypes, property syntax gets stricter parameter checks.

  73. 73. Can recent Node.js versions run a .ts file directly?

    Correct answer: Yes - it strips types, but doesn't type-check

    Type stripping removes types without transformation, so features that generate code (like enum) need extra flags or a compiler.

  74. 74. What type does a function parameter with a default value get?

    function paginate(page = 1) { /* ... */ }

    Correct answer: Inferred from the default, optional for callers

    Callers may omit the argument or pass undefined; inside the function page is always a number.

  75. 75. Why is @ts-expect-error safer than @ts-ignore?

    Correct answer: It errors once the next line has no error left

    Both silence the next line. Add a comment explaining why, and prefer fixing types where possible.