TypeScript · Lesson 9
React & Angular patterns
How TypeScript shows up in real React and Angular code (props, reducers, hooks, context, effects, DI, RxJS, signals), with the core mechanics rebuilt without the libraries.
In short
- Component variants are discriminated unions of props
- Type empty
useStatevalues; return hook tuplesas const - Cancel stale requests: effect cleanup or
switchMap - Angular injects by class or typed
InjectionToken - Signals for state, RxJS for events over time
In a React or Angular codebase most of the TypeScript isn't clever type-level code. It's a handful of patterns used over and over: props as unions, reducers over action unions, typed hooks, injected services, Observable pipelines and signals. This lesson shows those patterns as they appear in real code.
The snippets below use React, Angular and RxJS and are not executed. Exercises can't import libraries, so each one rebuilds the core mechanism in plain TypeScript: Angular-style form validators, a props union rendered to a string, a useReducer-style reducer, a Redux-like store, the stale-response guard behind switchMap, a small Observable with pipe, and Angular-style signals. The typing and the runtime ideas carry over directly to the real libraries.
React: props are types
A component's props are an ordinary type. When a component has variants that need different props, use a discriminated union instead of a bag of optional props, so invalid combinations don't compile:
type ButtonProps =
| { kind: 'button'; label: string; onClick: () => void }
| { kind: 'link'; label: string; href: string }
| { kind: 'icon'; icon: IconName; 'aria-label': string }; // required for accessibility
function Button(props: ButtonProps) {
switch (props.kind) {
case 'link': return <a className="btn" href={props.href}>{props.label}</a>;
case 'button': return <button className="btn" onClick={props.onClick}>{props.label}</button>;
case 'icon': return <button className="btn" aria-label={props['aria-label']}><Icon name={props.icon} /></button>;
}
}
Wrapping native elements. ComponentProps<'input'> is every prop <input> accepts. Intersect it with your own props and spread the rest, and use Omit to take over a native prop:
import type { ComponentProps } from 'react';
type TextFieldProps = Omit<ComponentProps<'input'>, 'size'> & { label: string; error?: string; size?: 'sm' | 'lg' };
function TextField({ label, error, size = 'sm', ...input }: TextFieldProps) {
return (
<label className={`field field-${size}`}>
{label}
<input aria-invalid={error ? true : undefined} {...input} />
{error && <span role="alert">{error}</span>}
</label>
);
}
Generic components infer their type parameter from the props, exactly like generic functions:
interface ListProps<T> {
items: readonly T[];
getKey: (item: T) => string;
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, getKey, renderItem }: ListProps<T>) {
return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}
<List items={users} getKey={(u) => u.id} renderItem={(u) => u.name} />; // T = User
(In a .tsx file a generic arrow function needs <T,> so it isn't parsed as JSX.)
React: state, reducers and hooks
useState infers from the initial value, which is often too narrow:
const [user, setUser] = useState<User | null>(null); // without <...>: the type is just null
const [tags, setTags] = useState<string[]>([]); // without <...>: never[]
For state with several related fields, use useReducer with a state union and an action union. The reducer is a pure function, so it's easy to unit test:
type State =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'error'; message: string }
| { status: 'done'; users: User[] };
type Action = { type: 'fetch' } | { type: 'failed'; message: string } | { type: 'loaded'; users: User[] };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'fetch': return { status: 'loading' };
case 'failed': return { status: 'error', message: action.message };
case 'loaded': return { status: 'done', users: action.users };
default: { const unhandled: never = action; return unhandled; }
}
}
const [state, dispatch] = useReducer(reducer, { status: 'idle' });
dispatch({ type: 'loaded', users }); // the payload is checked against the 'loaded' member
Custom hooks that return tuples need as const, otherwise TypeScript infers an array of a union:
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((v) => !v), []);
return [on, toggle] as const; // readonly [boolean, () => void], not (boolean | (() => void))[]
}
Context with a non-null guard. A context has no sensible default, so its type includes null. Wrap it in a hook that throws once, instead of checking for null in every consumer:
const AuthContext = createContext<AuthState | null>(null);
export function useAuth(): AuthState {
const auth = useContext(AuthContext);
if (!auth) throw new Error('useAuth must be used inside <AuthProvider>');
return auth; // narrowed to AuthState for every caller
}
Effects and stale responses. If the user types "a" and then "ab", two requests are in flight. If the "a" response arrives last, the UI shows results for the wrong query. Abort the previous request in the effect's cleanup:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then((r) => r.json() as Promise<User[]>)
.then(setResults)
.catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) setError(String(e));
});
return () => controller.abort(); // runs before the next effect run and on unmount
}, [query]);
Note that r.json() as Promise<User[]> is an assertion. Nothing checks that the server actually returned users, so validate untrusted data at the boundary.
Angular: services and dependency injection
Angular builds the object graph for you. Classes are their own injection tokens. For anything else (config objects, functions, interfaces) use a typed InjectionToken<T>:
export interface AppConfig { apiUrl: string; pageSize: number }
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly http = inject(HttpClient);
private readonly config = inject(APP_CONFIG); // typed AppConfig, inferred from the token
search(q: string): Observable<User[]> {
return this.http.get<User[]>(`${this.config.apiUrl}/users`, { params: { q } });
}
}
// app.config.ts
providers: [{ provide: APP_CONFIG, useValue: { apiUrl: '/api', pageSize: 20 } }];
inject() works in field initializers and constructors. It has largely replaced constructor-parameter injection because it composes better with inheritance and helper functions.
Angular: RxJS
HTTP calls, router events and form changes are Observables. You build pipelines with pipe, and each operator is an OperatorFunction<In, Out>, so types flow from step to step:
export class UserSearchComponent {
private readonly users = inject(UserService);
readonly query = new FormControl('', { nonNullable: true });
readonly results$: Observable<User[]> = this.query.valueChanges.pipe(
debounceTime(300),
map((q) => q.trim()),
filter((q) => q.length >= 2),
distinctUntilChanged(),
switchMap((q) => this.users.search(q)), // unsubscribes from the previous request
);
}
switchMap is the RxJS answer to the stale-response problem: a new query cancels the old request. (mergeMap keeps all of them, concatMap queues them, exhaustMap ignores new ones while busy.) The async pipe in a template subscribes and unsubscribes for you. A manual subscribe needs cleanup, and takeUntilDestroyed() ties it to the component's lifetime:
constructor() {
this.route.paramMap.pipe(takeUntilDestroyed()).subscribe((params) => this.load(params.get('id')));
}
A forgotten unsubscribe is one of the most common sources of memory leaks in Angular apps. The RxJS & Observables topic goes much deeper, with the real library.
Angular: signals
Signals are synchronous reactive values with automatic dependency tracking. They're the default for component state in modern Angular:
export class CartComponent {
readonly items = signal<CartItem[]>([]);
readonly total = computed(() => this.items().reduce((sum, i) => sum + i.price * i.qty, 0));
readonly currency = input.required<string>(); // signal-based @Input
constructor() {
effect(() => localStorage.setItem('cart', JSON.stringify(this.items())));
}
add(item: CartItem) {
this.items.update((list) => [...list, item]); // new array: signals compare with Object.is
}
}
computed is lazy and cached, and it recomputes only when something it read has changed. effect re-runs when its dependencies change. Use signals for state and RxJS for events over time, and convert between them with toSignal / toObservable.
Strict templates. With "strictTemplates": true in angularCompilerOptions, templates are type-checked too: [user]="selected()" must match the input's type, $event is typed, and @if (user(); as u) narrows. React gets this for free because JSX is TypeScript.
The exercises
| Exercise | Real-world counterpart |
|---|---|
| Form validators | Angular Validators and ValidatorFn, form error messages, react-hook-form validate |
| Variant props | discriminated-union props, aria-label rules |
| Signup wizard reducer | useReducer, NgRx reducers, typed form fields |
| Typed store | Redux / Zustand / NgRx store, useSelector |
| Latest-only calls | effect cleanup with AbortController, switchMap |
| Mini RxJS | Observable, pipe, map / filter / take, teardown |
| Signals | Angular signal, computed, effect, untracked |
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app