Coding Interviews (TypeScript)
⭐ Interview Importance: HIGH
⏱️ Revision Time: 4 min
TL;DR
When writing standard algorithms (like LeetCode) in a TypeScript interview, your primary focus should be on defining the core data structures (Interfaces) before you write the logic. Keep the typing strict, but avoid overly complex generic gymnastics unless explicitly asked.
Strategy for Live Coding
- Define Interfaces First: If the problem involves moving a Robot on a Grid, write
interface Point { x: number; y: number }andtype Direction = "N" | "S" | "E" | "W". This shows architecture skills. - Use Enums/Unions for State: Instead of arbitrary strings, use union types or enums to represent states (e.g.,
status: "idle" | "running"). - Use
MapandSetwith Types: Instead of generic objects{}for caching/memoization, usenew Map<string, number>(). It is much safer and shows you know modern JS/TS.
Challenge 1: The Generic Cache
Prompt: Implement a generic key-value Cache class with an expiration time.
class Cache<K, V> {
private store = new Map<K, { value: V; expiresAt: number }>();
set(key: K, value: V, ttlMs: number): void {
this.store.set(key, {
value,
expiresAt: Date.now() + ttlMs
});
}
get(key: K): V | null {
const item = this.store.get(key);
if (!item) return null;
if (Date.now() > item.expiresAt) {
this.store.delete(key);
return null;
}
return item.value;
}
}
Challenge 2: The API Fetcher
Prompt: Write a wrapper around fetch that takes a URL, strictly types the JSON response, and handles network errors safely using the Result pattern.
// Define the Result Monad
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
// The Generic Fetch function
async function safeFetch<T>(url: string): Promise<Result<T>> {
try {
const response = await fetch(url);
if (!response.ok) {
return { success: false, error: `HTTP ${response.status}` };
}
// JSON.parse returns 'any', so we cast it to our Generic T
const data = await response.json() as T;
return { success: true, data };
} catch (err: unknown) {
// Safe error handling!
if (err instanceof Error) {
return { success: false, error: err.message };
}
return { success: false, error: "Unknown Network Error" };
}
}
Challenge 3: Type Guards
Prompt: Given an array of mixed data (User | Admin | string)[], write a function that extracts ONLY the Admins.
interface User { type: "user"; name: string; }
interface Admin { type: "admin"; role: string; }
type MixedData = User | Admin | string;
// The Custom Type Guard
function isAdmin(item: MixedData): item is Admin {
return typeof item === "object" && item !== null && "type" in item && item.type === "admin";
}
function getAdmins(data: MixedData[]): Admin[] {
// Because of the type guard, .filter() knows it returns Admin[] !
return data.filter(isAdmin);
}