Skip to content

TypeScript

Q (basic): Why TypeScript? What does it actually give you?

Say this (30 sec): TypeScript adds static types on top of JavaScript. It catches bugs at compile time — typos, wrong props, null access — gives great autocomplete and safe refactoring, and acts as documentation. It compiles to plain JS, and the types are erased, so there’s zero runtime cost but also zero runtime checking.

Follow-ups they ask: Does TS validate API responses? → No. If the API returns something different, TS won’t know. Validate at the boundary with Zod/Valibot and infer the type from the schema.

Common wrong answer: “TypeScript makes the app faster / checks types at runtime.” Neither is true.

Q (basic): type vs interface?

Say this (30 sec): Both can describe object shapes. Differences: interface can be reopened (declaration merging) and extended with extends; type can’t be reopened but can describe anything — unions, tuples, primitives, mapped and conditional types. I use interface for public object shapes and component props when I might extend them, and type for unions and computed types. Consistency within a codebase matters more than the choice.

Example:

interface User { id: string; name: string }
interface Admin extends User { role: "admin" }
type Status = "idle" | "loading" | "success" | "error"; // only type can do this
type Point = [number, number];
type WithTimestamps<T> = T & { createdAt: Date };
interface Window { myGlobal: string } // merges into the built-in Window

Follow-ups they ask: extends vs &? → extends reports conflicts as errors; intersection & of conflicting properties silently produces never for that property.

Q (basic): any vs unknown vs never?

Say this (30 sec): any disables type checking — you can do anything, so bugs slip through. unknown is the type-safe version: it accepts any value, but you must narrow it before using it. never means a value that never exists — a function that always throws, or the leftover type after all union cases are handled.

Example:

function parse(json: string): unknown { return JSON.parse(json); }
const data = parse("{}");
data.name; // error: data is unknown
if (typeof data === "object" && data !== null && "name" in data) {
data.name; // ok after narrowing
}
function fail(msg: string): never { throw new Error(msg); }

Follow-ups they ask: What type is e in catch (e)? → unknown under strict (via useUnknownInCatchVariables). Narrow with if (e instanceof Error).

Q (basic): void vs undefined vs never as return types?

Say this (30 sec): void means “the return value isn’t meant to be used.” undefined means it literally returns undefined. never means the function never returns normally — it throws or loops forever.

Example:

function log(msg: string): void { console.log(msg); }
function crash(): never { throw new Error("x"); }
Q (basic): What is narrowing? Name the ways to narrow.

Say this (30 sec): Narrowing is TypeScript refining a broad type to a more specific one based on checks in your code. Ways: typeof, instanceof, in operator, equality/truthiness checks, discriminated unions (checking a shared literal field), and custom type guards.

Example:

function format(input: string | number | Date) {
if (typeof input === "string") return input.toUpperCase();
if (typeof input === "number") return input.toFixed(2);
return input.toISOString(); // must be Date here
}
Q (mid): What is a discriminated union? Why is it useful?

Say this (30 sec): It’s a union of object types that all share a literal field — like status or type — so TS can narrow by checking that field. Perfect for API/request state and reducer actions, because it makes impossible states impossible: you can’t have data while status is "error".

Example:

type FetchState<T> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: string };
function render(s: FetchState<User>) {
switch (s.status) {
case "loading": return "Loading...";
case "success": return s.data.name; // data available only here
case "error": return s.error;
}
}
Q (mid): How do you do an exhaustive check with never?

Say this (30 sec): In the default branch, assign the value to a never variable. If someone adds a new union member and forgets to handle it, the value isn’t never anymore, so compilation fails.

Example:

type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number };
function area(s: Shape) {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "square": return s.side ** 2;
default: {
const _exhaustive: never = s; // error if a new kind is added
return _exhaustive;
}
}
}
Q (mid): What is a custom type guard (user-defined type predicate)?

Say this (30 sec): A function that returns value is SomeType. When it returns true, TS narrows the variable to that type in the calling code. Useful for validating unknown data or filtering arrays.

Example:

interface Cat { meow(): void }
function isCat(pet: unknown): pet is Cat {
return typeof pet === "object" && pet !== null && "meow" in pet;
}
const values = [1, null, 2, undefined];
const nums = values.filter((v): v is number => v != null); // number[]

Follow-ups they ask: Risk? → TS trusts your predicate; if the logic is wrong, the type is a lie. Also, TS 5.5+ infers predicates for simple filters like .filter(x => x !== null) automatically.

Q (basic): What are generics? Give an example.

Say this (30 sec): Generics are type parameters — like function arguments, but for types. They let one function, hook or component work with many types while preserving the specific type, instead of falling back to any.

Example:

function first<T>(arr: T[]): T | undefined {
return arr[0];
}
first([1, 2]); // number | undefined
first(["a", "b"]); // string | undefined
interface ApiResponse<T> { data: T; error: string | null }
async function getJson<T>(url: string): Promise<T> {
const res = await fetch(url);
return res.json() as Promise<T>; // note: a cast, not validation
}
Q (mid): What are generic constraints?

Say this (30 sec): T extends Something restricts what types can be passed, so you can safely use properties of Something inside. Combined with keyof, it lets you write type-safe property access.

Example:

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "A", age: 22 };
getProp(user, "age"); // number
getProp(user, "email"); // error: not a key of user
function longest<T extends { length: number }>(a: T, b: T) {
return a.length >= b.length ? a : b;
}
Q (mid): How do you type a generic React component?

Say this (30 sec): Declare the type parameter on the function. Then the prop types flow through — e.g. a List where renderItem gets the correct item type.

Example:

type ListProps<T> = {
items: T[];
renderItem: (item: T) => React.ReactNode;
getKey: (item: T) => string;
};
function List<T>({ items, renderItem, getKey }: ListProps<T>) {
return <ul>{items.map((i) => <li key={getKey(i)}>{renderItem(i)}</li>)}</ul>;
}
// In a .tsx arrow function, write <T,> so it isn't parsed as JSX.
Q (basic): Name the common utility types.

Say this (30 sec):

  • Partial<T> — all props optional (update payloads)
  • Required<T> — all props required
  • Readonly<T> — all props readonly
  • Pick<T, K> / Omit<T, K> — keep / remove keys
  • Record<K, V> — object with keys K and values V
  • Exclude<U, X> / Extract<U, X> — filter union members
  • NonNullable<T> — remove null and undefined
  • ReturnType<F>, Parameters<F>, Awaited<T>

Example:

interface User { id: string; name: string; email: string; password: string }
type PublicUser = Omit<User, "password">;
type UserUpdate = Partial<Pick<User, "name" | "email">>;
type Roles = Record<"admin" | "user", string[]>;
type Status = Exclude<"idle" | "loading" | "error", "idle">; // "loading" | "error"
type Data = Awaited<ReturnType<typeof fetchUser>>;
Q (mid): What do keyof and typeof do in types?

Say this (30 sec): keyof T gives a union of a type’s keys. Type-level typeof value gets the type of a JS value. Combined, keyof typeof obj gives the keys of a real object — very handy for config maps.

Example:

const routes = { home: "/", about: "/about", blog: "/blog" } as const;
type RouteName = keyof typeof routes; // "home" | "about" | "blog"
type RoutePath = (typeof routes)[RouteName]; // "/" | "/about" | "/blog"

Follow-ups they ask: What does as const do? → makes the value deeply readonly and keeps literal types ("/" instead of string).

Q (mid): What are mapped types?

Say this (30 sec): Mapped types build a new type by looping over keys of another: { [K in keyof T]: ... }. That’s how Partial, Readonly and Record are implemented. You can add/remove modifiers with ?, -?, readonly, and rename keys with as.

Example:

type MyPartial<T> = { [K in keyof T]?: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string }>; // { getName: () => string }
Q (tricky): What are conditional types and infer? (brief)

Say this (30 sec): A extends B ? X : Y picks a type based on a condition. infer extracts a type from inside another type. Built-ins like ReturnType use this. On a union, conditional types distribute over each member.

Example:

type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type ElementOf<T> = T extends (infer U)[] ? U : never;
type X = ElementOf<string[]>; // string
Q (mid): Enums vs union of string literals?

Say this (30 sec): Most modern TS code prefers string literal unions. Enums generate real runtime JavaScript (an object), numeric enums accept any number in some cases, and they don’t work with Node’s type-stripping / erasableSyntaxOnly mode. Unions are zero-cost, autocomplete well, and work directly with API strings. If I need a runtime list of values, I use an as const object and derive the type.

Example:

// union
type Role = "admin" | "editor" | "viewer";
// as const object when you need runtime values too
const ROLES = ["admin", "editor", "viewer"] as const;
type Role2 = (typeof ROLES)[number];
// enum (emits JS)
enum Direction { Up = "UP", Down = "DOWN" }

Follow-ups they ask: const enum? → inlined at compile time, but problematic with isolatedModules (used by Vite/Next/esbuild), so usually avoided.

Q (mid): What does satisfies do? How is it different from a type annotation?

Say this (30 sec): satisfies checks that a value matches a type, but keeps the narrower inferred type of the value. A normal annotation (: Type) widens the variable to that type and you lose specific info.

Example:

type Colors = Record<string, string | [number, number, number]>;
const a: Colors = { red: [255, 0, 0], green: "#0f0" };
a.green.toUpperCase(); // error: could be a tuple
const b = { red: [255, 0, 0], green: "#0f0" } satisfies Colors;
b.green.toUpperCase(); // ok — TS knows green is a string
b.blue; // error — key doesn't exist (annotation would allow it)

Follow-ups they ask: Where in Next.js? → e.g. export default { ... } satisfies Config in config files, and satisfies Metadata.

Q (mid): Type assertion (as) vs non-null assertion (!) — when are they risky?

Say this (30 sec): as tells the compiler “trust me, it’s this type” — no runtime check, so if you’re wrong it crashes at runtime. ! says “this isn’t null/undefined.” Both bypass safety, so I prefer narrowing. Acceptable cases: DOM elements I know exist, or after validation.

Example:

const el = document.getElementById("root")!; // ok if you control the HTML
const canvas = document.querySelector("canvas") as HTMLCanvasElement;
const user = (await res.json()) as User; // risky — prefer Zod parse
Q (basic): What does strict mode in tsconfig enable?

Say this (30 sec): "strict": true turns on a family of checks, most importantly strictNullChecks (null/undefined aren’t assignable everywhere) and noImplicitAny (no silent any). It also enables strict function types, strictPropertyInitialization, useUnknownInCatchVariables, and others. Every new project should have it on. Extra useful flag: noUncheckedIndexedAccess, which makes arr[i] return T | undefined.

Follow-ups they ask: Other tsconfig options you know? → target, module/moduleResolution (bundler for Vite/Next), paths for @/ aliases, jsx, noEmit (when a bundler does the compiling), isolatedModules.

Q (basic): How do you type props, events and state in React with TS?

Say this (30 sec): Type props with a type/interface. Event handlers use React’s event types. useState usually infers; give it a generic when the initial value is null or an empty array.

Example:

type ButtonProps = React.ComponentProps<"button"> & { variant?: "primary" | "ghost" };
function Button({ variant = "primary", ...rest }: ButtonProps) {
return <button data-variant={variant} {...rest} />;
}
const [user, setUser] = useState<User | null>(null);
const [items, setItems] = useState<string[]>([]);
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setQuery(e.target.value);
const inputRef = useRef<HTMLInputElement>(null);

Follow-ups they ask: React.FC? → it works, but most teams just type props directly on the function; it no longer adds implicit children (since React 18 types).

Q (mid): What is structural typing?

Say this (30 sec): TypeScript compares types by their shape, not by their name. If two types have compatible properties, they’re assignable, even if declared separately. That’s different from Java/C# nominal typing.

Example:

interface Point { x: number; y: number }
const p = { x: 1, y: 2, z: 3 };
const q: Point = p; // ok — has x and y
const r: Point = { x: 1, y: 2, z: 3 }; // error — excess property check on object literals

Follow-ups they ask: Why does the second one error but not the first? → excess property checks only apply to fresh object literals.

Q (mid): How do you share types between frontend and backend?

Say this (30 sec): Options: a shared types package in a monorepo; define Zod schemas once and infer types with z.infer, using the same schema to validate on the server; or end-to-end typed tools like tRPC or Hono RPC. In Next.js, server actions and server components already share types naturally since it’s the same codebase.

Example:

import { z } from "zod";
export const SignupSchema = z.object({ email: z.email(), password: z.string().min(8) });
export type SignupInput = z.infer<typeof SignupSchema>;