TypeScriptとは?JavaScriptとの違いと導入メリット
2026年現在、フロントエンド・バックエンド問わずTypeScriptはJavaScript開発の事実上の標準言語となっています。Microsoftが開発したTypeScriptは、JavaScriptに静的型システムを追加することで、大規模開発の品質を劇的に向上させます。
| 比較項目 | JavaScript | TypeScript |
|---|---|---|
| 型チェック | 実行時のみ | コンパイル時に検出 |
| IDE補完 | 基本的 | 高精度 |
| リファクタリング | 困難 | 安全・容易 |
TypeScriptの基本型システム
プリミティブ型と基本的な型注釈
// 基本的な型注釈
const name: string = "Tech Athletes";
const age: number = 5;
const isActive: boolean = true;
// 配列型
const numbers: number[] = [1, 2, 3];
const names: Array<string> = ["Alice", "Bob"];
// オブジェクト型
const user: { name: string; age: number; email?: string } = {
name: "Taro",
age: 25
};
Union型・Intersection型・Literal型
// Union型:複数の型のいずれか
type Status = "active" | "inactive" | "pending";
type StringOrNumber = string | number;
// Literal型:特定の値のみ許可
type Direction = "north" | "south" | "east" | "west";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
// Discriminated Union(判別可能なUnion)
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
インターフェースと型エイリアス
// Interface:拡張可能なオブジェクト型定義
interface User {
readonly id: number;
name: string;
email: string;
age?: number;
}
interface AdminUser extends User {
role: "admin" | "superadmin";
permissions: string[];
}
// Utility Types
type UpdateUserInput = Partial<User>;
type PublicUser = Pick<User, "id" | "name" | "email">;
type SafeUser = Omit<User, "password">;
ジェネリクス(Generics)
// ジェネリック関数
function identity<T>(arg: T): T {
return arg;
}
// 制約付きジェネリクス
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// ジェネリッククラス
class Repository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
findById(id: number): T | undefined {
return this.items.find(item => item.id === id);
}
}
tsconfig.jsonの最適化
{
"compilerOptions": {
"target": "ES2022",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"forceConsistentCasingInFileNames": true
}
}
まとめ:TypeScript習得のロードマップ
- 基礎:型注釈、基本型、インターフェース(1〜2週間)
- 中級:ジェネリクス、Utility Types、型ガード(2〜4週間)
- 上級:Conditional Types、Template Literal Types(1〜3ヶ月)
- 実践:React/Next.jsプロジェクトへの適用
TypeScriptはJavaScriptエンジニアの必須スキルです。本記事を参考に、ぜひ実践的なプロジェクトに適用してみてください。