Generics · TypeScript + React
Write reusable, type-safe abstractions with generics. Master constraints, keyof, and the built-in utility types Partial, Pick, Omit, Record. Type your React components properly: props, state, refs, and event handlers. Just enough TypeScript to make React feel like a proper language.
What you'll learn
- 1Write generic functions and classes
- 2Constrain type parameters with extends
- 3Use keyof to refer to property names
- 4Apply utility types: Partial, Required, Pick, Omit, Record
- 5Type component props with type or interface
- 6Type useState and useReducer
- 7Type event handlers correctly
- 8Use children: React.ReactNode and forwardRef
Generics
Write reusable, type-safe abstractions with generics. Master constraints, keyof, and the built-in utility types Partial, Pick, Omit, Record.
1. Generic Functions
function identity<T>(value: T): T {
return value;
}
const n = identity(42); // T inferred as number
const s = identity<string>("a"); // explicit
function first<T>(arr: T[]): T | undefined {
return arr[0];
}2. Constraints with extends
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("hello", "hi");
longest([1,2,3], [4,5]);3. keyof
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Alice" };
const n = getProp(user, "id"); // number
const s = getProp(user, "name"); // string
// getProp(user, "email"); // error4. Utility Types
| Utility | Effect |
|---|---|
| Partial<T> | All properties optional |
| Required<T> | All properties required |
| Pick<T, K> | Pick a subset of keys |
| Omit<T, K> | Remove keys |
| Record<K, V> | Build an object type with given keys/values |
| Readonly<T> | All properties readonly |
| ReturnType<F> | Return type of a function |
type User = { id: number; name: string; email: string };
type UserUpdate = Partial<User>; // { id?, name?, email? }
type UserName = Pick<User, "name">; // { name: string }
type NoEmail = Omit<User, "email">;
type UsersById = Record<number, User>; // { [id: number]: User }TypeScript + React
Type your React components properly: props, state, refs, and event handlers. Just enough TypeScript to make React feel like a proper language.
1. Typed Props
type ButtonProps = {
label: string;
onClick: () => void;
variant?: "primary" | "secondary";
children?: React.ReactNode;
};
function Button({ label, onClick, variant = "primary", children }: ButtonProps) {
return (
<button className={`btn btn-${variant}`} onClick={onClick}>
{label}
{children}
</button>
);
}2. useState
// Usually inferred:
const [count, setCount] = useState(0); // number
// Explicit when the initial value does not tell the full story:
const [user, setUser] = useState<User | null>(null);
const [items, setItems] = useState<string[]>([]);3. Event Handlers
function Form() {
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input onChange={handleChange} />
</form>
);
}4. Refs and Custom Hooks
function AutoFocus() {
const ref = useRef<HTMLInputElement>(null);
useEffect(() => { ref.current?.focus(); }, []);
return <input ref={ref} />;
}
function useToggle(initial = false): [boolean, () => void] {
const [on, setOn] = useState(initial);
return [on, () => setOn(v => !v)];
}All lecture materials and example code are openly available on GitHub.
View on GitHub ↗Comments 0
No comments yet. Be the first.
Only members can comment.
Comments with ads, abuse, personal information or illegal content are hidden or removed. Comments are shown with your nickname. Privacy Policy