How do you use TypeScript effectively in a React codebase?
What the interviewer wants to hear
- Type props with interfaces or types, including children and event handlers
- Use discriminated unions for variants and state machines
- Use generics for reusable components such as lists, tables and selects
- Treat API data as unknown and validate it at the boundary, for example with Zod
- Enable strict mode and avoid any; prefer inference where it is clear
Model answer
I turn on strict mode from day one and avoid any, because each any switches off checking for everything it touches. For components, I type props with a type or interface, including children as React.ReactNode and callbacks with exact signatures, and I extend native element props, such as React.ComponentProps<"button">, so wrappers accept every standard attribute. I let inference handle local variables and hook state where it is obvious. For components that change shape, I use discriminated unions, for example a button that is either a link with href or a button with onClick, so invalid combinations do not compile. The same idea works for request state: loading, error with a message, or success with data. Reusable pieces like a Select or Table use generics so the item type flows through to callbacks. Finally, types do not exist at runtime, so I validate API responses at the boundary with a schema library like Zod and infer the types from the schema.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Frontend Developer questions
- Explain the JavaScript event loop, including microtasks and macrotasks.
- How do you decide where to keep state in a React app: local state, context, a store, or a server-cache library?
- A page has a poor LCP score. How would you investigate and fix it?
- What testing strategy would you use for a frontend application?
- Explain client-side rendering, server-side rendering and static site generation. When would you use each?
- What happens between typing a URL in the browser and seeing the page rendered? Focus on the frontend side.
- A React screen feels slow. How do you find and reduce unnecessary re-renders?
- How do you handle loading, error and empty states when a screen fetches data from an API?
- How would you handle user authentication and tokens in a single-page app or Next.js frontend?