TypeScript
/Intermediate
Live Coding: TypeScript Algorithms
Definition
Typical technical interview questions requiring the use of TypeScript to solve algorithmic problems while maintaining strict type safety.
Explain Like I'm New
In modern interviews, solving the algorithm isn't enough. If the role requires TypeScript, the interviewer will penalize you for using `any`, failing to define generic types, or writing unsafe object mutations.
Real World Example
Writing a `groupBy` function that groups an array of objects by a specific key, returning a strictly typed Dictionary object.
Common Use Cases
- •Technical interviews
- •Building strongly-typed utility libraries (like Lodash)
Interactive Example
// INTERVIEW QUESTION: // Write a strongly typed 'groupBy' function. // BAD (The JS way): // function groupBy(arr, key) { ... } // EXCELLENT (The TS way): // 1. T is the object inside the array // 2. K is the specific key we want to group by (Must be a key of T) function groupBy<T, K extends keyof T>( array: T[], key: K ): Record<string, T[]> { // Return type is a dictionary where values are arrays of T return array.reduce((accumulator, item) => { // We cast to string because object keys must be strings/symbols const groupValue = String(item[key]); if (!accumulator[groupValue]) { accumulator[groupValue] = []; } accumulator[groupValue].push(item); return accumulator; }, {} as Record<string, T[]>); } const users = [ { role: 'admin', name: 'Alice' }, { role: 'user', name: 'Bob' }, { role: 'admin', name: 'Charlie' } ]; const grouped = groupBy(users, 'role'); // TS knows exactly what 'grouped' looks like! console.log(grouped.admin.length); // 2
Interview Questions
basic
- Why will an interviewer penalize you for using `any` during a TS interview?
intermediate
- Implement a strictly-typed `groupBy` function.
advanced
- How do you type a deeply nested object flattening algorithm?