この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:4
ページ更新者:爽健
更新日時:2026-06-11 07:07:02

タイトル: TypeScript
SEOタイトル: TypeScript 完全ガイド

この記事の要点
  • TypeScript は Microsoft が開発する JavaScript のスーパーセット言語
  • 静的型付けを JavaScript に追加し、コンパイル時にエラー検出
  • 最終的には JavaScript にコンパイルされて実行される (型情報は実行時には消える)
  • React / Vue / Angular / Svelte / Next.js などフロントエンドフレームワークは TypeScript ファーストに移行
  • Deno / Bun はトランスパイル不要で TS を直接実行できる

TypeScript とは

TypeScript は Microsoft が 2012 年に発表した、JavaScript に静的型付けを加えた言語です。JavaScript の構文を完全に包含し (スーパーセット)、コンパイラ (tsc) で JavaScript にトランスパイルして実行します。

TypeScript ロゴ

2026 年現在、フロントエンド開発の事実上のデフォルト言語になっており、React・Vue・Svelte・Angular・Next.js などのフレームワークは TypeScript ベースで設計・配布されています。

TypeScript の特徴

特徴説明
静的型付け変数・引数・戻り値に型を付け、コンパイル時にチェック
型推論明示しなくても初期値や式から型を推論
JavaScript 互換既存 JS コードはそのまま TS として動く (拡張子変更のみ)
強力な型システムGenerics / Union / Discriminated Union / Conditional Type
エディタ補完VS Code 等で強力な補完・リファクタリング
段階的導入any// @ts-ignore で徐々に型付けできる

JavaScript との違い

// JavaScript (拡張子 .js)
function add(a, b) {
  return a + b;
}
add(1, 2);        // 3
add("1", "2");    // "12" ← 文字列連結になっても気付かない
add(1);           // NaN  ← b が undefined

// TypeScript (拡張子 .ts)
function add(a: number, b: number): number {
  return a + b;
}
add(1, 2);        // 3
add("1", "2");    // ❌ コンパイルエラー
add(1);           // ❌ コンパイルエラー (引数不足)

インストールと初期化

# Node.js プロジェクトに導入
npm init -y
npm install --save-dev typescript @types/node

# tsconfig.json を生成
npx tsc --init

# .ts ファイルをコンパイル
npx tsc index.ts          # → index.js

# 監視モード
npx tsc --watch

# 実行 (Node 直接実行は不可、tsx か ts-node 経由)
npm install --save-dev tsx
npx tsx index.ts

tsconfig.json (設定ファイル)

{
  "compilerOptions": {
    "target": "ES2022",                  // 出力 JS のバージョン
    "module": "ESNext",                  // モジュール形式
    "moduleResolution": "bundler",       // バンドラ前提の解決
    "lib": ["ES2022", "DOM"],            // 利用可能な API
    "jsx": "react-jsx",                  // JSX 設定 (React 18+)

    "strict": true,                      // 厳格モード (全て ON)
    "noImplicitAny": true,               // 暗黙の any 禁止
    "strictNullChecks": true,            // null/undefined 厳格
    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "esModuleInterop": true,             // CommonJS との互換
    "skipLibCheck": true,                // .d.ts のチェックを省略 (高速化)
    "forceConsistentCasingInFileNames": true,

    "outDir": "./dist",
    "rootDir": "./src",
    "sourceMap": true,                   // デバッグ用
    "declaration": true                  // .d.ts も出力
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Strict モード

新規プロジェクトでは必ず "strict": true を有効にします。これで以下が一気に有効になります:

  • noImplicitAny - 暗黙の any 禁止
  • strictNullChecks - null/undefined を別の型として扱う
  • strictFunctionTypes - 関数型の引数共変・反変
  • strictBindCallApply - bind/call/apply の型チェック
  • strictPropertyInitialization - クラスプロパティ初期化必須
  • alwaysStrict - 出力 JS に "use strict"

型推論

多くの場合、明示的に型を書かなくても TS が推論してくれます:

let name = "山田";          // string と推論
let age = 30;               // number と推論
let items = [1, 2, 3];      // number[] と推論

const arr = ["a", "b", 1];  // (string | number)[] と推論

// 関数の戻り値も推論
function double(x: number) {
  return x * 2;             // 戻り値型 number と推論
}

// オブジェクトリテラル
const user = { name: "山田", age: 30 };
// → { name: string; age: number; } と推論

Generics (ジェネリクス)

// 任意の型を受け取る関数
function identity(value: T): T {
  return value;
}
identity("hello");   // string が返る
identity(42);                // T が number と推論される

// 配列ユーティリティ
function first(arr: T[]): T | undefined {
  return arr[0];
}

// クラス
class Stack {
  private items: T[] = [];
  push(item: T) { this.items.push(item); }
  pop(): T | undefined { return this.items.pop(); }
}
const s = new Stack();
s.push(1);

Union Types と Discriminated Union

// Union: 複数の型のいずれか
type ID = string | number;
function getUser(id: ID) {
  if (typeof id === "string") {
    // ここでは id は string
  } else {
    // ここでは id は number
  }
}

// Discriminated Union (タグ付きユニオン)
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "rect"; width: number; height: number };

function area(s: Shape): number {
  switch (s.kind) {
    case "circle":  return Math.PI * s.radius ** 2;
    case "square":  return s.size ** 2;
    case "rect":    return s.width * s.height;
  }
}

Decorators / Enum / Namespace

// Enum
enum Color { Red, Green, Blue }
enum Status { Active = "active", Inactive = "inactive" }

// const enum (ビルド時にリテラル展開、軽い)
const enum Direction { Up, Down, Left, Right }

// Namespace (古い、現代は module/import 推奨)
namespace MyApp {
  export function greet(name: string) {
    console.log(`Hello, ${name}`);
  }
}
MyApp.greet("world");

// Decorator (実験的、TS 5.0 で標準化)
function log(target: any, key: string, desc: PropertyDescriptor) {
  const orig = desc.value;
  desc.value = function(...args: any[]) {
    console.log(`[${key}]`, args);
    return orig.apply(this, args);
  };
}

class Calc {
  @log
  add(a: number, b: number) { return a + b; }
}

JSX (React で利用)

// 拡張子は .tsx
import React from 'react';

interface Props {
  name: string;
  age?: number;
}

const Greet: React.FC = ({ name, age }) => {
  return (
    

Hello, {name}

{age &&

Age: {age}

}
); };

実行ランタイム比較

ランタイムTS 対応備考
Node.js要トランスパイルtsc / tsx / ts-node 経由
Denoネイティブ対応.ts を直接実行
Bunネイティブ対応.ts / .tsx そのまま、超高速
ブラウザ不可ビルドして JS にする

主要フレームワークの TS サポート

  • React: create-react-app --template typescript や Next.js で完全対応
  • Vue 3: TS first 設計。