ES6+medium
TypeScript patterns for scalable frontend code
Explain how TypeScript improves frontend correctness and maintainability. Cover interfaces vs types, unions, generics, strict null checks, API typing, and component props.
Asked at Tenable
Answer
Interview framing: TypeScript is valuable when it models contracts between components, API responses, and business logic. The goal is not "more types"; it is fewer invalid states.
Key points:
- type vs interface:
- Use interface for object shapes that may be extended.
- Use type for unions, intersections, primitives, tuples, and mapped types.
- Union types:
- Model finite states explicitly: loading | success | error is better than many optional booleans.
- Generics:
- Useful for reusable helpers/components where input and output types are related.
- Example: ApiResponse, SelectOption, Repository.
- Strict null checks:
- Force you to handle missing data from APIs and async flows.
- Prefer narrowing over non-null assertions.
- API boundaries:
- TypeScript checks compile-time assumptions, but API data is runtime input.
- Use schema validation (zod/io-ts/custom validators) for untrusted responses.
- Component props:
- Keep prop types expressive but small.
- Avoid passing huge objects when a component only needs a few fields.
Pitfalls:
- any disables the value of TypeScript.
- Overly clever types can make code hard to maintain.
- Types should encode domain invariants, not fight the implementation.
Source: Tenable frontend job description