TypeScriptとは?JavaScriptとの違い
TypeScriptはMicrosoftが開発したJavaScriptの上位互換言語です。静的型付けを追加することで、大規模アプリケーション開発での安全性・保守性を大幅に向上させます。
TypeScriptを使うメリット
- コンパイル時のエラー検出でバグを事前に防ぐ
- IDEの補完・リファクタリングサポートが強力
- コードの自己文書化(型が仕様書になる)
- チーム開発でのコード品質向上
環境構築とプロジェクト初期化
# TypeScriptのインストール
npm install -g typescript
# バージョン確認
tsc --version
# プロジェクト初期化
npm init -y
npm install typescript @types/node ts-node
npx tsc --init # tsconfig.jsonを生成
tsconfig.jsonの推奨設定
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
基本的な型システム
// プリミティブ型
const name: string = 'Tech Athletes';
const age: number = 30;
const isActive: boolean = true;
const data: null = null;
const value: undefined = undefined;
// 配列型
const numbers: number[] = [1, 2, 3];
const names: Array = ['Alice', 'Bob'];
// オブジェクト型
const user: { id: number; name: string; email?: string } = {
id: 1,
name: 'kasata',
};
// ユニオン型
type ID = string | number;
const userId: ID = 'user-123';
// リテラル型
type Direction = 'north' | 'south' | 'east' | 'west';
const heading: Direction = 'north';
インターフェースと型エイリアス
// インターフェース定義
interface User {
id: number;
name: string;
email: string;
age?: number; // オプショナル
readonly createdAt: Date; // 読み取り専用
}
// インターフェースの継承
interface AdminUser extends User {
role: 'admin' | 'superadmin';
permissions: string[];
}
// 型エイリアス
type ApiResponse = {
data: T;
status: number;
message: string;
timestamp: Date;
};
// 使用例
const response: ApiResponse = {
data: { id: 1, name: 'test', email: 'test@example.com', createdAt: new Date(), role: 'admin', permissions: ['read', 'write'] },
status: 200,
message: 'Success',
timestamp: new Date()
};
ジェネリクス
// ジェネリック関数
function first(arr: T[]): T | undefined {
return arr[0];
}
const firstNum = first([1, 2, 3]); // number
const firstStr = first(['a', 'b']); // string
// ジェネリッククラス
class Repository {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
findById(id: number): T | undefined {
return (this.items as any[]).find(item => item.id === id);
}
getAll(): T[] {
return [...this.items];
}
}
// 型制約
function getProperty(obj: T, key: K): T[K] {
return obj[key];
}
ReactとTypeScriptの組み合わせ
import React, { useState, useCallback, FC } from 'react';
// Propsの型定義
interface ButtonProps {
label: string;
onClick: (event: React.MouseEvent) => void;
variant?: 'primary' | 'secondary' | 'danger';
disabled?: boolean;
children?: React.ReactNode;
}
// コンポーネント定義
const Button: FC = ({ label, onClick, variant = 'primary', disabled = false, children }) => {
return (
{children || label}
);
};
// カスタムフックの型定義
function useLocalStorage(key: string, initialValue: T): [T, (value: T) => void] {
const [storedValue, setStoredValue] = useState(() => {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = useCallback((value: T) => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
}, [key]);
return [storedValue, setValue];
}
まとめ
TypeScriptは現代のJavaScript開発において事実上の標準となっています。型安全性による開発効率の向上、IDEサポートの強化、大規模チームでのコード品質維持など、そのメリットは多岐にわたります。まずstrictモードで小さなプロジェクトから始め、徐々に高度な型パターンを習得していきましょう。