Advertisement

Index Signatures & Record Types interview questions and answers

10 Index Signatures & Record Types interview questions for TypeScript roles, each with a model answer, examples and likely follow-ups.

10 questions
Advertisement

10 questions

Q1 Beginner Save

What is an index signature and what problem does it solve?

An index signature describes the type of ALL properties an object can have when the exact set of key names isn't known ahead of time, using the syntax `{ [key: string]: ValueType }` — it lets you type dictionary-like objects with dynamic keys.
interface Scores {
  [studentName: string]: number;
}
const scores: Scores = { alice: 90, bob: 85 };
scores.carol = 78; // allowed, matches the index signature
Real-world example
Typing a lookup object where keys come from user input or external data and aren't known in advance, like a scores-by-name map.
Likely follow-ups
  • Can an index signature's key type be something other than string or number?
Types & Interfaces
Q2 Beginner Save

What is the built-in Record<K, V> utility type, and how does it relate to an index signature?

Record<K, V> is a built-in utility type equivalent to `{ [key in K]: V }` — it's the more concise, commonly preferred way to express a dictionary-like object type where K is typically a string, number, or union of literal types and V is the value type.
type Scores = Record<string, number>;
const scores: Scores = { alice: 90, bob: 85 };

type Role = 'admin' | 'user' | 'guest';
type RolePermissions = Record<Role, string[]>;
Real-world example
Typing a lookup table keyed by a known finite set of literal values, like Record<Role, Permissions>.
Likely follow-ups
  • How does Record<K, V> behave differently when K is a union of literals versus a plain 'string'?
Mapped Types
Q3 Intermediate Save

How do you combine an index signature with specific, explicitly-named required properties?

You can mix known properties with an index signature, but every explicitly-named property's type must be ASSIGNABLE to the index signature's value type, since the index signature effectively promises every property (named or not) conforms to that value type.
interface Config {
  name: string;         // must be compatible with the index signature's value type
  [key: string]: string; // allows any other string-valued property too
}
const config: Config = { name: 'App', theme: 'dark', version: '1.0' };
Real-world example
Modeling a configuration object with a few known required fields plus arbitrary additional string settings.
Likely follow-ups
  • What compiler error occurs if a named property's type conflicts with the index signature's value type?
Types & Interfaces
Q4 Intermediate Save

Why does TypeScript allow reading a property from an object typed with a string index signature even if that exact key doesn't actually exist at runtime, and how does noUncheckedIndexedAccess change this?

By default, TypeScript trusts the index signature's promise and types every access (even to keys that may not exist) as the declared value type, WITHOUT undefined — this is technically unsound. Enabling noUncheckedIndexedAccess makes indexed access return `ValueType | undefined` instead, correctly reflecting that the key might not actually be present.
interface Scores { [name: string]: number; }
const scores: Scores = { alice: 90 };
const bobScore = scores.bob; // typed as 'number' by default, but is actually undefined at runtime!

// With noUncheckedIndexedAccess: true
// bobScore would be typed as 'number | undefined' instead
Real-world example
Catching a real class of runtime bugs where code assumes every dynamic lookup succeeds, only to get undefined unexpectedly.
Likely follow-ups
  • Why isn't noUncheckedIndexedAccess enabled by default, given it catches real bugs?
Nullability: strictNullChecks Optional Chaining & Nullish Coalescing
Q5 Intermediate Save

How do you use a Record type with a union of string literals as keys to enforce that ALL cases are handled?

Record<UnionOfLiterals, ValueType> requires an object literal assigned to it to include EVERY member of the union as a key — omitting one causes a compile error, making it a lightweight way to enforce exhaustive handling of a fixed set of cases in object form (as an alternative to a switch statement).
type Theme = 'light' | 'dark' | 'system';
const themeLabels: Record<Theme, string> = {
  light: 'Light Mode',
  dark: 'Dark Mode',
  system: 'Use System Setting'
  // omitting any key here is a compile error
};
Real-world example
Guaranteeing a lookup table of labels/icons/colors stays in sync with every possible value of a status or theme union.
Likely follow-ups
  • What error message appears if you forget one of the required keys?
Discriminated Unions & Exhaustiveness Checking
Q6 Advanced Save

Why can't you have both a string index signature and a NUMBER index signature with incompatible value types on the same interface?

JavaScript actually coerces numeric keys to strings under the hood (obj[1] and obj['1'] access the same property), so TypeScript requires that a number index signature's value type be assignable to the string index signature's value type when both exist together, ensuring consistency for keys that could be accessed either way.
interface Bad {
  [index: string]: string;
  // [index: number]: number; // Error: numeric index type not assignable to string index type
}
interface Good {
  [index: string]: string | number;
  [index: number]: number; // OK: number is assignable to (string | number)
}
Real-world example
Understanding a specific and somewhat obscure compiler error when trying to type an array-like object with mixed access patterns.
Likely follow-ups
  • In practice, when would a class or object realistically need both index signature types together?
Structural Typing & Duck Typing
Q7 Advanced Save

How do you use Record<K, V> in combination with Partial<> to type a lookup object where not every key is guaranteed to be populated yet?

Wrap the Record type in Partial<> to make every key optional, which is the correct way to model an incrementally-built lookup object (like a cache or accumulator) that doesn't necessarily have every possible key populated from the start.
type Theme = 'light' | 'dark' | 'system';
const cache: Partial<Record<Theme, string>> = {};
cache.light = 'Light Mode'; // OK
console.log(cache.dark); // typed as string | undefined, correctly reflecting it may not exist yet
Real-world example
Modeling an in-memory cache keyed by a known finite set of values that gets populated gradually over the program's lifetime.
Likely follow-ups
  • Why is `Partial<Record<K,V>>` generally more correct here than a plain `Record<K, V>` with all keys pre-populated as empty strings?
Readonly const Assertions & Immutability
Q8 Advanced Save

How would you write a mapped type using an index signature-like syntax that also applies key remapping via 'as'?

Combine a mapped type's `[K in Keys]` syntax with the 'as' clause to transform each resulting key name (e.g. prefixing it), producing a new object type whose keys are systematically derived from — but different from — the original key set, unlike a plain index signature which can't rename keys.
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
interface Person { name: string; age: number; }
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }
Real-world example
Auto-generating a getter-method interface from a plain data interface, avoiding manual duplication.
Likely follow-ups
  • Could a plain index signature achieve this same key-renaming effect on its own?
Mapped Types
Q9 Advanced Save

How do you constrain an index signature's key type to only specific string patterns using template literal types?

Combine a mapped type (since plain index signatures only support generic string/number/symbol, not literal patterns) with a template literal type as the key pattern, letting you type objects whose keys must follow a specific naming convention, like a CSS-variable-style prefix.
type CssVariables = {
  [K in `--${string}`]: string
};
const styles: CssVariables = {
  '--primary-color': '#3366ff',
  '--font-size': '16px'
  // 'color': 'red' // Error: doesn't match the '--${string}' pattern
};
Real-world example
Typing a CSS custom-properties object where every key must start with '--', catching typos in variable naming.
Likely follow-ups
  • How does this differ in capability from a plain `[key: string]: string` index signature?
Template Literal Types
Q10 Advanced Save

How would you implement a type-safe 'groupBy' function whose return type is a Record keyed by the actual grouping values encountered?

Constrain the grouping function's return type to `string | number | symbol` (valid key types), then type the result as `Record<ReturnType<typeof keyFn>, T[]>` using generics — though in practice, since the SET of actual keys present depends on runtime data, the more honest and accurate typing uses `Partial<Record<K, T[]>>`, since not every possible key is guaranteed to appear.
function groupBy<T, K extends string | number | symbol>(
  items: T[],
  keyFn: (item: T) => K
): Partial<Record<K, T[]>> {
  const result: Partial<Record<K, T[]>> = {};
  for (const item of items) {
    const key = keyFn(item);
    (result[key] ??= []).push(item);
  }
  return result;
}
Real-world example
Building a fully type-safe, reusable groupBy utility (similar to lodash's) with accurate optional-key typing.
Likely follow-ups
  • Why is `Partial<Record<K, T[]>>` a more honest return type here than a non-partial `Record<K, T[]>`?
Generics