PROGスクールナビ

TypeScript中級・上級テクニック|型システムの高度な活用法

TypeScriptの型システムを使いこなせると、バグを事前に防ぎ大規模なコードを安全に保守できます。基礎の次に習得すべき中〜上級テクニックを解説します。

ジェネリクス(型パラメータ)

// 型に柔軟性を持たせる
function identity(arg: T): T {
  return arg;
}

const num = identity(42);     // T = number
const str = identity('hello'); // T = string

// ジェネリクスを使ったAPIレスポンス型
type ApiResponse = {
  data: T;
  status: number;
  message: string;
};

const userResponse: ApiResponse = {
  data: { id: 1, name: '太郎' },
  status: 200,
  message: 'OK'
};

// ジェネリクスの制約(extends)
function getProperty(obj: T, key: K): T[K] {
  return obj[key];
}
const name = getProperty({ name: '太郎', age: 25 }, 'name'); // string型

Union型とIntersection型

// Union型(または)
type StringOrNumber = string | number;
type Status = 'pending' | 'active' | 'inactive';

// 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;
  }
}

// Intersection型(かつ)
type Admin = User & { adminLevel: number };

Mapped型・条件型

// Mapped型(全プロパティを変換)
type Readonly = {
  readonly [K in keyof T]: T[K];
};

type Optional = {
  [K in keyof T]?: T[K];
};

// 条件型(型によって分岐)
type IsArray = T extends any[] ? true : false;

type A = IsArray; // true
type B = IsArray;   // false

// Infer(型推論)
type UnpackArray = T extends Array ? U : T;
type Unpacked = UnpackArray; // string

Utility Types(組み込みの便利な型)

type User = {
  id: number;
  name: string;
  email: string;
  age?: number;
};

// Partial:全プロパティをオプショナルに
type PartialUser = Partial;
// { id?: number; name?: string; email?: string; age?: number }

// Required:全プロパティを必須に
type RequiredUser = Required;

// Pick:一部のプロパティだけ選択
type UserBasic = Pick;
// { id: number; name: string; }

// Omit:一部のプロパティを除外
type UserWithoutId = Omit;

// Record:オブジェクト型を定義
type PageConfig = Record;

型ガード(Type Guard)

// instanceof による型ガード
function processInput(input: string | Error): string {
  if (input instanceof Error) {
    return input.message; // ここではError型
  }
  return input.toUpperCase(); // ここではstring型
}

// カスタム型ガード(is演算子)
function isUser(obj: unknown): obj is User {
  return (
    typeof obj === 'object' &&
    obj !== null &&
    'id' in obj &&
    'name' in obj
  );
}

まとめ

TypeScript上級技術はジェネリクス→Utility Types→Mapped型・条件型の順で習得するのがおすすめ。型で安全なAPIクライアントやReactコンポーネントを書けるようになると、実務で大きく評価されます。

📚 プログラミング初心者におすすめの本

🛒 楽天で人気のプログラミング入門書