TypeScriptとは
TypeScriptはMicrosoftが開発したJavaScriptのスーパーセットで、静的型付けを追加した言語です。大規模なフロントエンド・バックエンド開発において、バグの早期発見と開発効率の向上に貢献します。
JavaScriptとの比較
// JavaScript(型エラーが実行時まで分からない)
function add(a, b) {
return a + b;
}
add("5", 3); // "53"(意図しない文字列結合)
// TypeScript(コンパイル時にエラー検出)
function add(a: number, b: number): number {
return a + b;
}
add("5", 3); // エラー: Argument of type 'string' is not assignable to 'number'
基本的な型
// プリミティブ型
let name: string = "田中";
let age: number = 30;
let active: boolean = true;
// 配列
let scores: number[] = [80, 90, 75];
let tags: Array<string> = ["tech", "dev"];
// オブジェクト型(インターフェース)
interface User {
id: number;
name: string;
email?: string; // ?で任意プロパティ
}
// 関数の型
function greet(user: User): string {
return `こんにちは、${user.name}さん`;
}
強力な型機能
// ユニオン型
type Status = "active" | "inactive" | "pending";
let userStatus: Status = "active";
// ジェネリクス
function identity<T>(arg: T): T {
return arg;
}
// 型ガード
function process(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value * 2;
}
// Utility Types
type Partial<T> = { [P in keyof T]?: T[P] };
type ReadOnly<T> = { readonly [P in keyof T]: T[P] };
tsconfig.jsonの設定
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"outDir": "./dist",
"rootDir": "./src"
}
}
TypeScriptの学習ロードマップ
| レベル | 習得事項 |
|---|---|
| 入門 | 基本型・インターフェース |
| 中級 | ジェネリクス・Utility Types |
| 上級 | 条件型・Template Literal Types |
strict: trueを有効にして最初から型安全な習慣をつけることが、TypeScript上達の近道です。





