Overview
Curated: · Written: · Reviewed:
TypeScript for Frontend Engineers
In one line
TypeScript is a build-time shape checker: it proves what the compiler can see and erases everything else. Reach for it to make illegal states unrepresentable in components, hooks and API types, and add runtime validation wherever data enters from outside.
Key definitions
- Structural typing: assignability by shape. Extra members are fine, missing ones fail.
- Excess property check: applies to object literals only, not to variables that already hold the extra keys.
- Discriminated union: members share a literal field, such as
kind, that narrows the rest of the shape. - Type predicate:
x is T. The compiler trusts the function's result and never verifies its body. - Declaration merging: same-named interfaces combine. Type aliases do not.
- Exhaustiveness: passing the leftover case to a
neverparameter turns a missing case into a compile error.
How it works
tscchecks the whole program, then erases every annotation, interface and generic. The runtime runs plain JavaScript.- The compiler tracks each binding through its branches. Each
typeof,in,instanceofor discriminant check removes possibilities. ascasts and predicates skip the check or trust it. Neither emits code, so a wrong one fails only at runtime.- Generics infer type arguments from call-site values. A constraint such as
T extends { id: string }rejects callers whose values lack the member.
When to use and when not to
| Choice | Reach for it when | Avoid it when |
|---|---|---|
| Discriminated union | state has mutually exclusive shapes | one optional field describes the state |
type alias | unions, mapped and derived types | you need declaration merging |
interface | a public object shape consumers may augment | you need a union or mapped type |
| Generic parameter | the caller's value decides the type | one concrete type is correct |
| Type predicate | a real runtime check backs it | the body is a guess |
| Schema parse | data crosses a network, storage or URL boundary | data is already typed internally |
enum | almost never; prefer string unions or as const objects | under isolatedModules, since const enum is problematic |
Traps interviewers probe
- Treating a response annotation as validation.
r.json()isPromise<any>andas Useronly records a claim. Fix: type the body asunknown, parse it with a schema inside the hook, and throw there, before any component renders. - Assuming excess property checks always fire.
const opts = { retries: 3, timeout: 30_000 }; f(opts)passes because the variable is not a fresh literal. Fix: pass the literal, or make the function read every key it accepts, so a droppedtimeoutcannot hide. - Freezing state or refs to the wrong type.
useState('idle' as const)locks the type to'idle'. Fix:useState<Status>('idle').useRef<HTMLDivElement>(null)is nullable on purpose; fix the call withref.current?.scrollIntoView(), not a non-null assertion. - Extracting a handler without annotating it.
function h(e) {}is implicit any. Fix: annotate the event with the element it is attached to, such asReact.ChangeEvent<HTMLInputElement>orReact.MouseEvent<HTMLButtonElement>. - Silencing a
nevererror. It means the reducer lacks a case. Fix: add the case. Do not cast, and do not delete the exhaustive default.
Interview tips
Open with the model: types are erased, so they prove shape at build time and prove nothing at runtime.
Follow-ups to expect:
- What TypeScript does not catch: network data,
anyleaks, lying casts, runtime invariants. typeversusinterface: merging, stricterextendsoverrides, unions only withtype.satisfieskeeps literal types and still checks the shape. An annotation widens them.as constkeeps literals but checks nothing.- Generic arrow components in
.tsxneed<T,>or<T extends unknown>, because a bare<T>parses as a JSX tag. - Context:
createContext<T | null>(null)with a hook that throws when the provider is missing. - Variance: method syntax is bivariant, while function-typed props are checked contravariantly under
strictFunctionTypes. - Derive, do not redeclare:
Omit,Pick,Awaited<ReturnType<typeof fn>>, and key remapping with template literals. - Module boundaries: type-only re-exports need
export typeunderisolatedModulesorverbatimModuleSyntax. swc and esbuild strip types, sotsc --noEmitruns as its own CI job. - Untyped dependencies:
@types/*first, then a hand-writtendeclare modulefile. Module augmentation works only on interfaces.
30-second outline:
- Definition: TypeScript checks shape before the program runs and erases every type.
- Mechanism: narrowing through discriminants and checks;
nevercatches missing cases. - Limit: nothing checks runtime data, so validate at each I/O boundary.
- Example: a discriminated union for request state, with a
neverdefault, and a schema parse in the fetch hook.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.