記事一覧に戻る

TypeScript 5.0の新機能:デコレーターから型システムの改善まで

4分で読む
Tech Blog Admin
TypeScript 5.0の新機能:デコレーターから型システムの改善まで
広告スペース
Slot: article-top
Format: horizontal
本番環境でGoogle AdSenseが表示されます

TypeScript 5.0の革新的な進化

2023年3月にリリースされたTypeScript 5.0は、多くの新機能と改善をもたらしました。この記事では、その中でも特に重要な機能について詳しく見ていきます。

1. デコレーターの正式サポート

TypeScript 5.0で、ついにECMAScript準拠のデコレーターが正式にサポートされました。

function logged(value: any, context: any) {
  console.log(`${context.name} が呼び出されました`);
  return value;
}

class Example {
  @logged
  greet(name: string) {
    return `Hello, ${name}!`;
  }
}

クラスデコレーターの例

function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class BugReport {
  type = "report";
  title: string;
  
  constructor(t: string) {
    this.title = t;
  }
}

2. const Type Parameters

ジェネリック型パラメータにconst修飾子を追加できるようになりました。

// 以前のコード
function getNames<T extends readonly string[]>(names: T): T {
  return names;
}

// TypeScript 5.0
function getNames<const T extends readonly string[]>(names: T): T {
  return names;
}

// より正確な型推論
const names = getNames(['Alice', 'Bob', 'Charlie']);
// type: readonly ["Alice", "Bob", "Charlie"]

3. satisfies演算子の活用

satisfies演算子により、型の検証と推論のバランスが改善されました。

type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];

const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
  blue: [0, 0, 255]
} satisfies Record<Colors, string | RGB>;

// paletteの型は保持されつつ、型チェックも行われる
const redValue = palette.red[0]; // OK: number
const greenValue = palette.green.toUpperCase(); // OK: string

4. 型システムの改善

Enum改善

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

// TypeScript 5.0ではより良い型推論
function move(direction: Direction) {
  switch (direction) {
    case Direction.Up:
      // より正確な型ナローイング
      break;
  }
}

Union型の改善

type Result<T> = 
  | { success: true; value: T }
  | { success: false; error: Error };

function processResult<T>(result: Result<T>) {
  if (result.success) {
    // TypeScript 5.0でより良い型推論
    console.log(result.value); // T型として正しく推論
  } else {
    console.error(result.error.message);
  }
}

5. パフォーマンスの大幅な改善

TypeScript 5.0では、コンパイル速度が大幅に向上しました:

  • ビルド時間: 平均10-25%高速化
  • メモリ使用量: 最大20%削減
  • エディタのレスポンス: より高速な補完とエラー検出

最適化の例

// 大規模なプロジェクトでの型推論が高速化
type DeepReadonly<T> = {
  readonly [P in keyof T]: T[P] extends object 
    ? DeepReadonly<T[P]> 
    : T[P];
};

// 複雑な型操作のパフォーマンスが向上
type UnionToIntersection<U> = 
  (U extends any ? (k: U) => void : never) extends 
  ((k: infer I) => void) ? I : never;

6. 新しいコンパイラオプション

{
  "compilerOptions": {
    "verbatimModuleSyntax": true,
    "allowArbitraryExtensions": true,
    "customConditions": ["development", "production"]
  }
}

実践的な活用例

APIレスポンスの型安全な処理

interface ApiResponse<T> {
  data: T;
  status: number;
  timestamp: string;
}

async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
  const response = await fetch(url);
  const data = await response.json();
  
  return {
    data,
    status: response.status,
    timestamp: new Date().toISOString()
  } satisfies ApiResponse<T>;
}

// 使用例
const userResponse = await fetchData<User>('/api/users/1');
console.log(userResponse.data.name); // 型安全

まとめ

TypeScript 5.0は、開発者体験を大幅に向上させる多くの改善をもたらしました。特にデコレーターの正式サポートと型システムの改善により、より表現力豊かで型安全なコードが書けるようになりました。

これらの新機能を活用することで、より保守性の高い、バグの少ないアプリケーションを開発できるでしょう。

広告スペース
Slot: article-bottom
Format: rectangle
本番環境でGoogle AdSenseが表示されます

関連記事