Generic и полиморфные компоненты
На этой странице
Generic-компонент параметризуется типом данных: function Select<T>({ items, getLabel, onChange }: Props<T>) — TypeScript выводит T из переданных items, и onChange получает элемент правильного типа без приведений. Так типизируют списки, таблицы, селекты, автокомплиты. Полиморфный компонент принимает проп as и рендерит нужный элемент или компонент (<Text as="label" htmlFor="x">), а его props меняются в зависимости от as — для этого используют ComponentPropsWithoutRef<T> и Omit. Полезные утилиты React-типов: ComponentProps<typeof X> (взять props существующего компонента), ComponentPropsWithoutRef<'button'> (расширить нативный элемент), PropsWithChildren, ReactNode. В .tsx generic у стрелочной функции пишут <T,>, чтобы не путать с JSX.
Вопрос
Как типизировать переиспользуемые компоненты, которые работают с разными типами данных? Что такое полиморфный компонент с пропом as?
Generic-список
type ListProps<T> = {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => React.ReactNode;
empty?: React.ReactNode;
};
export function List<T>({ items, getKey, renderItem, empty = 'Пусто' }: ListProps<T>) {
if (items.length === 0) return <p>{empty}</p>;
return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}type Book = { id: number; title: string; year: number };
<List
items={books} // T выведен как Book
getKey={(b) => b.id}
renderItem={(b) => `${b.title}, ${b.year}`} // b: Book — автокомплит работает
/>Без generic пришлось бы писать items: unknown[] и приводить типы в каждом колбэке.
Generic-селект с ограничением
type SelectProps<T extends { id: string | number }> = {
options: T[];
value: T | null;
onChange: (value: T) => void;
getLabel: (option: T) => string;
label: string;
};
export function Select<T extends { id: string | number }>({ options, value, onChange, getLabel, label }: SelectProps<T>) {
return (
<label>
{label}
<select
value={value?.id ?? ''}
onChange={(e) => {
const next = options.find((o) => String(o.id) === e.target.value);
if (next) onChange(next);
}}
>
<option value="" disabled>Выберите…</option>
{options.map((o) => <option key={o.id} value={o.id}>{getLabel(o)}</option>)}
</select>
</label>
);
}T extends { id: ... } — ограничение: любой тип, но с полем id.
// Стрелочная функция в .tsx: запятая отличает generic от JSX-тега
const Badge = <T,>({ value }: { value: T }) => <span>{String(value)}</span>;Расширение нативных элементов
import type { ComponentPropsWithoutRef } from 'react';
type ButtonProps = ComponentPropsWithoutRef<'button'> & {
variant?: 'primary' | 'ghost';
loading?: boolean;
};
export function Button({ variant = 'primary', loading, disabled, children, ...rest }: ButtonProps) {
return (
<button {...rest} disabled={disabled || loading} data-variant={variant} aria-busy={loading}>
{children}
</button>
);
}Все нативные атрибуты (type, onClick, aria-*) доступны и типизированы. В React 19 ref — обычный prop: если нужно его принимать, используй ComponentPropsWithRef<'button'>.
// Взять props чужого компонента
type LinkProps = React.ComponentProps<typeof Link>;Полиморфный компонент с as
import type { ComponentPropsWithoutRef, ElementType, ReactNode } from 'react';
type TextProps<T extends ElementType> = {
as?: T;
size?: 'sm' | 'md' | 'lg';
children: ReactNode;
} & Omit<ComponentPropsWithoutRef<T>, 'as' | 'size' | 'children'>;
export function Text<T extends ElementType = 'span'>({ as, size = 'md', children, ...rest }: TextProps<T>) {
const Component = as ?? 'span';
return <Component data-size={size} {...rest}>{children}</Component>;
}<Text>Обычный текст</Text>
<Text as="label" htmlFor="email">Email</Text> // htmlFor разрешён — это label
<Text as="a" href="/books">Каталог</Text> // href разрешён
<Text as={Link} href="/books">Каталог</Text> // props компонента Link
<Text as="span" href="/x">Ошибка</Text> // ✗ TS: у span нет hrefВместо as многие дизайн-системы используют паттерн asChild (Radix Slot): компонент передаёт свои props и классы единственному ребёнку — <Button asChild><Link href="/x">…</Link></Button>. Типизация проще, а семантику определяет сам ребёнок.
Полезные типы
| Тип | Для чего |
|---|---|
ReactNode | Всё, что можно отрендерить (children) |
ReactElement | Именно JSX-элемент |
ComponentPropsWithoutRef<'input'> | Props нативного элемента |
ComponentProps<typeof X> | Props существующего компонента |
PropsWithChildren<P> | Добавить children |
ElementType | Тег или компонент (для as) |
Dispatch<SetStateAction<T>> | Тип сеттера из useState |
React.JSX.Element | Возвращаемый тип компонента (глобальный JSX устарел в React 19) |
Что важно помнить
- Дай TypeScript вывести generic из данных — явно указывать
<List<Book>>нужно редко. - Ограничения (
extends) описывают минимальный контракт. - Полиморфные компоненты мощные, но усложняют типы и сообщения об ошибках; для дизайн-систем часто проще
asChild.
Мини-шпаргалка
function List<T>({ items }: Props<T>) — T выводится из items
<T extends { id: string }> — ограничение
const C = <T,>(...) => ... — generic у стрелки в .tsx
ComponentPropsWithoutRef<'button'> — расширить нативный элемент
ComponentProps<typeof X> — props чужого компонента
as + ElementType + Omit<ComponentPropsWithoutRef<T>, ...> — полиморфизм