react-typescript について
TypeScriptでReactを開発する人向けの型付けリファレンススキルです。イベントやプロパティの型、再利用可能なジェネリクス、ユーティリティ型、型安全なContextを扱います。
主な機能
- 01プロパティと子要素の型付け
- 02Reactイベントハンドラーの型
- 03型付きHookとContext
- 04再利用可能なジェネリックコンポーネント
- 05ユーティリティ型と状態の判別共用体
活用シーン
- 01コンポーネントのプロパティと子要素の定義
- 02ジェネリックなリストやテーブルの構築
- 03Context ProviderとHookの型付け
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ josiahsiegel/ claude-plugin-marketplace --skill react-typescriptインストール後、Claude Code で/react-typescriptを入力して読み込まれたか確認します。
同梱ファイルreferences/generics-utilities-context.md
詳細
クイックリファレンス
| 種類 | 用途 | 例 |
|---|---|---|
| Props インターフェース | コンポーネントの Props | interface ButtonProps { variant: 'primary' } |
ReactNode | 子要素 | children: ReactNode |
ChangeEvent | 入力の変更 | (e: ChangeEvent<HTMLInputElement>) |
FormEvent | フォームの送信 | (e: FormEvent<HTMLFormElement>) |
MouseEvent | クリック | (e: MouseEvent<HTMLButtonElement>) |
| パターン | 例 |
|---|---|
| HTML Props を拡張 | extends ButtonHTMLAttributes<HTMLButtonElement> |
| ジェネリックコンポーネント | function List<T>({ items }: { items: T[] }) |
| forwardRef | forwardRef<HTMLInputElement, Props> |
| 判別可能なユニオン | { status: 'success'; data: T } | { status: 'error'; error: Error } |
| ユーティリティ型 | 目的 |
|---|---|
Partial<T> | すべての Props を省略可能にする |
Pick<T, K> | 特定の Props を選択する |
Omit<T, K> | 特定の Props を除外する |
ComponentProps<'button'> | 要素の Props を取得する |
このスキルを使用する場面
React と TypeScript の統合に使用します:
- コンポーネントの Props と子要素に型を付ける
- 適切な型でイベントを処理する
- ジェネリックな再利用可能コンポーネントを構築する
- 型安全なコンテキストとフックを作成する
- Props を操作するためにユーティリティ型を使用する
- 多態性コンポーネントを実装する
React の基本について:react-fundamentals-19 を参照してください
React と TypeScript
コンポーネントの Props
基本的な Props の型
// Inline props type
function Greeting({ name, age }: { name: string; age: number }) {
return <p>Hello {name}, you are {age} years old</p>;
}
// Interface for props
interface UserCardProps {
name: string;
email: string;
avatar?: string; // Optional prop
role: 'admin' | 'user' | 'guest'; // Union type
}
function UserCard({ name, email, avatar, role }: UserCardProps) {
return (
<div className="user-card">
{avatar && <img src={avatar} alt={name} />}
<h3>{name}</h3>
<p>{email}</p>
<span className={`badge-${role}`}>{role}</span>
</div>
);
}
// Type alias
type ButtonVariant = 'primary' | 'secondary' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg';
type ButtonProps = {
variant?: ButtonVariant;
size?: ButtonSize;
children: React.ReactNode;
onClick?: () => void;
};
function Button({ variant = 'primary', size = 'md', children, onClick }: ButtonProps) {
return (
<button className={`btn btn-${variant} btn-${size}`} onClick={onClick}>
{children}
</button>
);
}
子要素の Props
import { ReactNode, PropsWithChildren } from 'react';
// Using ReactNode
interface CardProps {
title: string;
children: ReactNode;
}
function Card({ title, children }: CardProps) {
return (
<div className="card">
<h2>{title}</h2>
{children}
</div>
);
}
// Using PropsWithChildren
type ContainerProps = PropsWithChildren<{
className?: string;
}>;
function Container({ className, children }: ContainerProps) {
return <div className={className}>{children}</div>;
}
// Render prop children
interface DataFetcherProps<T> {
url: string;
children: (data: T, loading: boolean) => ReactNode;
}
function DataFetcher<T>({ url, children }: DataFetcherProps<T>) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
// ... fetch logic
return <>{children(data as T, loading)}</>;
}
HTML 要素の Props の拡張
import { ButtonHTMLAttributes, InputHTMLAttributes, forwardRef } from 'react';
// Extend button props
interface CustomButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary';
isLoading?: boolean;
}
const CustomButton = forwardRef<HTMLButtonElement, CustomButtonProps>(
({ variant = 'primary', isLoading, children, className, disabled, ...props }, ref) => {
return (
<button
ref={ref}
className={`btn btn-${variant} ${className || ''}`}
disabled={disabled || isLoading}
{...props}
>
{isLoading ? 'Loading...' : children}
</button>
);
}
);
CustomButton.displayName = 'CustomButton';
// Extend input props
interface TextInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> {
label: string;
error?: string;
size?: 'sm' | 'md' | 'lg';
}
const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
({ label, error, size = 'md', className, ...props }, ref) => {
return (
<div className="form-field">
<label>{label}</label>
<input
ref={ref}
className={`input input-${size} ${error ? 'input-error' : ''} ${className || ''}`}
{...props}
/>
{error && <span className="error-message">{error}</span>}
</div>
);
}
);
TextInput.displayName = 'TextInput';
多態性コンポーネント
import { ElementType, ComponentPropsWithoutRef, ReactNode } from 'react';
type PolymorphicProps<E extends ElementType> = {
as?: E;
children: ReactNode;
} & Omit<ComponentPropsWithoutRef<E>, 'as' | 'children'>;
function Box<E extends ElementType = 'div'>({
as,
children,
...props
}: PolymorphicProps<E>) {
const Component = as || 'div';
return <Component {...props}>{children}</Component>;
}
// Usage
function App() {
return (
<>
<Box>Default div</Box>
<Box as="section" className="section">Section element</Box>
<Box as="a" href="/about">Link element</Box>
<Box as="button" onClick={() => console.log('clicked')}>Button</Box>
</>
);
}
イベントハンドラー
一般的なイベント型
import {
ChangeEvent,
FormEvent,
MouseEvent,
KeyboardEvent,
FocusEvent,
DragEvent,
} from 'react';
function EventExamples() {
// Input change
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
};
// Select change
const handleSelectChange = (e: ChangeEvent<HTMLSelectElement>) => {
console.log(e.target.value);
};
// Form submit
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
console.log(Object.fromEntries(formData));
};
// Button click
const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
console.log(e.clientX, e.clientY);
};
// Keyboard
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
console.log('Enter pressed');
}
};
// Focus
const handleFocus = (e: FocusEvent<HTMLInputElement>) => {
console.log('Focused:', e.target.name);
};
// Drag
const handleDragStart = (e: DragEvent<HTMLDivElement>) => {
e.dataTransfer.setData('text/plain', 'dragging');
};
return (
<form onSubmit={handleSubmit}>
<input onChange={handleInputChange} onKeyDown={handleKeyDown} onFocus={handleFocus} />
<select onChange={handleSelectChange}>
<option value="1">Option 1</option>
</select>
<div draggable onDragStart={handleDragStart}>Drag me</div>
<button onClick={handleClick}>Submit</button>
</form>
);
}
イベントハンドラーの Props
interface FormFieldProps {
onChange: (value: string) => void;
onBlur?: () => void;
}
function FormField({ onChange, onBlur }: FormFieldProps) {
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
onChange(e.target.value);
};
return <input onChange={handleChange} onBlur={onBlur} />;
}
// Generic event handler
interface ListItemProps<T> {
item: T;
onSelect: (item: T) => void;
onDelete?: (item: T) => void;
}
function ListItem<T extends { id: string; name: string }>({
item,
onSelect,
onDelete,
}: ListItemProps<T>) {
return (
<li>
<span onClick={() => onSelect(item)}>{item.name}</span>
{onDelete && <button onClick={() => onDelete(item)}>Delete</button>}
</li>
);
}
TypeScript を使ったフック
useState
import { useState } from 'react';
// Inferred type
const [count, setCount] = useState(0); // number
// Explicit type
const [user, setUser] = useState<User | null>(null);
// Union types
type Status = 'idle' | 'loading' | 'success' | 'error';
const [status, setStatus] = useState<Status>('idle');
// Complex state
interface FormState {
name: string;
email: string;
errors: Record<string, string>;
}
const [form, setForm] = useState<FormState>({
name: '',
email: '',
errors: {},
});
// Update partial state
setForm(prev => ({ ...prev, name: 'John' }));
useReducer
import { useReducer, Reducer } from 'react';
// State and action types
interface CounterState {
count: number;
step: number;
}
type CounterAction =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'reset' }
| { type: 'setStep'; payload: number };
// Reducer function
const counterReducer: Reducer<CounterState, CounterAction> = (state, action) => {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + state.step };
case 'decrement':
return { ...state, count: state.count - state.step };
case 'reset':
return { ...state, count: 0 };
case 'setStep':
return { ...state, step: action.payload };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0, step: 1 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'setStep', payload: 5 })}>Set Step to 5</button>
</div>
);
}
useRef
import { useRef, useEffect } from 'react';
function RefExamples() {
// DOM element ref
const inputRef = useRef<HTMLInputElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
// Mutable value ref
const countRef = useRef<number>(0);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
// Focus input on mount
inputRef.current?.focus();
// Access canvas context
const ctx = canvasRef.current?.getContext('2d');
if (ctx) {
ctx.fillRect(0, 0, 100, 100);
}
// Start timer
timerRef.current = setInterval(() => {
countRef.current += 1;
}, 1000);
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, []);
return (
<div>
<input ref={inputRef} />
<canvas ref={canvasRef} />
</div>
);
}
useContext
import { createContext, useContext, useState, ReactNode } from 'react';
// Theme context
interface Theme {
primary: string;
secondary: string;
mode: 'light' | 'dark';
}
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
toggleMode: () => void;
}
const ThemeContext = createContext<ThemeContextType | null>(null);
// Provider
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>({
primary: '#007bff',
secondary: '#6c757d',
mode: 'light',
});
const toggleMode = () => {
setTheme((prev) => ({
...prev,
mode: prev.mode === 'light' ? 'dark' : 'light',
}));
};
return (
<ThemeContext.Provider value={{ theme, setTheme, toggleMode }}>
{children}
</ThemeContext.Provider>
);
}
// Hook with type safety
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
}
// Usage
function ThemedButton() {
const { theme, toggleMode } = useTheme();
return (
<button
style={{ backgroundColor: theme.primary }}
onClick={toggleMode}
>
Toggle {theme.mode === 'light' ? 'Dark' : 'Light'} Mode
</button>
);
}
カスタムフック
import { useState, useEffect, useCallback } from 'react';
// Fetch hook with generics
interface UseFetchResult<T> {
data: T | null;
loading: boolean;
error: Error | null;
refetch: () => Promise<void>;
}
function useFetch<T>(url: string): UseFetchResult<T> {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err instanceof Error ? err : new Error('Unknown error'));
} finally {
setLoading(false);
}
}, [url]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch: fetchData };
}
// Usage
interface User {
id: number;
name: string;
email: string;
}
function UserProfile({ userId }: { userId: number }) {
const { data: user, loading, error } = useFetch<User>(`/api/users/${userId}`);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!user) return <div>No user found</div>;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
ジェネリックコンポーネント、型ユーティリティ、型安全なコンテキスト
ジェネリックコンポーネント(List<T>、Select<T>、Table<T>)、ユーティリティ型(Partial、Pick、Omit、Record、Extract、Exclude、ComponentProps、ComponentPropsWithRef、ComponentPropsWithoutRef)、API の状態を表す判別可能なユニオン、推論/条件型(infer、Awaited、PropsOf)、および型安全な Context ファクトリーパターン(createSafeContext)の完全なコードは references/generics-utilities-context.md にあります。再利用可能な型付きコンポーネントを構築するとき、React の Props 型ユーティリティを扱うとき、または型付けを厳密にした Context プロバイダーを接続するときは、このリファレンスを読み込んでください。
ベストプラクティス
| プラクティス | 例 |
|---|---|
| コンポーネントの Props には interface を使用する | interface ButtonProps { ... } |
| 明らかな場合は型推論を優先する | useState(0) と useState<number>(0) |
| 再利用可能なコンポーネントにはジェネリクスを使用する | List<T>、Select<T> |
| 状態には判別可能なユニオンを使用する | { status: 'success'; data: T } |
| 適切な型で forwardRef を使用する | forwardRef<HTMLButtonElement, Props> |
any を避け、必要なら unknown を使用する | catch (err: unknown) |
リテラル型には as const を使用する | ['a', 'b'] as const |
コメント
Markdown 対応