Careeroza
Generics and API Data
Generic List Component
type ListProps<T> = {
items: T[];
renderItem: (item: T) => React.ReactNode;
};
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>;
}
const users = <List items={[{ id: 1, name: 'Asha' }]} renderItem={(u) => u.name} />; // u is typed automaticallyTyping API Responses
type Product = { id: number; title: string; price: number };
async function getProducts(): Promise<Product[]> {
const res = await fetch('/api/products');
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json() as Promise<Product[]>;
}| Utility type | Meaning |
|---|---|
| Partial<User> | all fields optional (update forms) |
| Pick<User, "id" | "name"> | only some fields |
| Omit<User, "password"> | all fields except some |
| Record<string, number> | object with string keys and number values |
| React.ComponentProps<"button"> | all props of a native button |