TypeScript for UI
Make the type checker enforce the UI rules, so a missing state, alt text or label becomes a compile error instead of a bug. Follow the repo's existing tsconfig, lint rules and patterns first. The rules below fill the gaps.
1. Compiler baseline
- Turn on
strict: true. If the repo allows it, also enablenoUncheckedIndexedAccess,exactOptionalPropertyTypesandnoImplicitOverride. Don't loosen the existing config to make code compile. - Use modern module settings:
"module": "preserve"or"esnext"with"moduleResolution": "bundler"for apps built with a bundler;"verbatimModuleSyntax": true;import typefor type-only imports.
- Typecheck before you're done. Run
tsc --noEmit(or the repo's typecheck script) and finish only when it reports zero errors.
2. No escape hatches
- No
any. Useunknownand narrow it. - No
@ts-ignore. If an escape is truly needed, use@ts-expect-errorwith a one-line reason. - No non-null
!and noascasts to silence errors. Fix the type instead.- Exception:
as const. - Use
satisfiesto check a value against a type without widening it:const routes = {…} satisfies Record<string, Route>.
- Exception:
- Validate data at trust boundaries. API responses,
localStorage, URL params, form data andpostMessageareunknownuntil a schema parses them.- Use the repo's validator (Zod, Valibot, ArkType…) and infer types from the schema:
type User = z.infer<typeof User>. - Never cast
await res.json() as User.
- Use the repo's validator (Zod, Valibot, ArkType…) and infer types from the schema:
3. Model UI states so impossible ones can't exist
This rule enforces "loading, empty, error, success" from new-ui.
- Use discriminated unions, not boolean soup:
Avoidtype State<T> = | { status: "loading" } | { status: "error"; error: Error } | { status: "success"; data: T };isLoading+error?+data?together, which allows contradictory combinations. - Check every union exhaustively. Use
switchwith aneverdefault so adding a state forces every view to handle it:default: { const _exhaustive: never = state; return _exhaustive; } - Treat empty as a real state. Use
data.length === 0and render it. - Model variants with unions. Use literal unions (
"primary" | "secondary") oras constobjects instead ofenum.
4. Component props
- Type props explicitly. Use
type Props = {…}, orinterfaceif the repo prefers it. - Don't use
React.FC. Type the props parameter:function Button({ … }: Props). - Extend native elements instead of re-declaring their attributes.
- Write
type Props = ComponentPropsWithoutRef<"button"> & { variant?: Variant }and spread the rest onto the element. - This passes through
aria-*,type,disabledand event handlers for free.
- Write
- Make accessibility required in the type:
- Image components: require
alt: string, pluswidthandheight(oraspectRatio), so the image doesn't shift the layout. - Icon-only buttons: require an accessible name, e.g.
{ icon: Icon; label: string }, or a union that demandsaria-labelwhen there are no children. - Form fields: require
label.
- Image components: require
- Make mutually exclusive props a union, not optional fields. For example:
{ href: string } | { onClick: () => void }. - Children and polymorphism:
- Use
ReactNodefor children. - Use an
as/asChildprop only if the repo's component library already uses that pattern.
- Use
- Use
readonlyfor prop arrays and objects you don't mutate.
5. Events, refs, hooks
- Use the platform event types:
ChangeEvent<HTMLInputElement>,FormEvent<HTMLFormElement>,KeyboardEvent. Reade.currentTarget, note.targetcast. - Type refs with the element:
useRef<HTMLDivElement>(null). Forward refs the way the repo's React version does:refas a prop in React 19,forwardRefbefore that. - Let inference work.
- Annotate only where inference fails, e.g.
useState<User | null>(null). - Leave out return type annotations on components.
- Give exported utility functions explicit return types.
- Annotate only where inference fails, e.g.
- Custom hooks return objects, or
as consttuples.
6. Responsive and theming in types
- Name breakpoints, tokens and variants from a single
as constsource and derive the types from it:Don't use magic strings scattered through components.const breakpoints = { sm: "40rem", md: "64rem" } as const; type Breakpoint = keyof typeof breakpoints; - Use template literal types for constrained strings, e.g.
`${number}rem`and`--${string}`for CSS vars. - Type CSS custom properties through
CSSProperties & Record<--${string}, string>. Don't cast style objects.
7. Async and data
- Use the repo's data layer (TanStack Query, SWR, RSC, loaders…) and its typed results. Don't hand-roll fetch state in
useEffect. - Handle every
Promise. Nothing floats. Useawait,voidwith a comment, or a.catch. - Type errors as
unknownincatchand narrow withinstanceof Error.
Checklist before done
tsc --noEmitpasses with zero errors and lint is clean.- No new
any,ascasts,!assertions or@ts-ignore. - External data is parsed by a schema, not cast.
- UI states are a discriminated union, and every
switchis exhaustive withnever. - Accessibility props (alt, label, accessible name) and media dimensions are required by the types.
- Props extend native element props, and the rest is spread through.
- Tokens, breakpoints and variants come from a single
as constsource.