TypeScriptの高度な型をマスター:ジェネリクス、ユーティリティ型、条件型、型ガード。型安全な開発のための完全ガイド。
# TypeScript 型システム完全ガイド
堅牢で型安全なアプリケーションを構築するための高度なTypeScriptコンセプトを学びましょう。
## ジェネリクス(汎用型)
```typescript
// ジェネリック関数
function firstElement<T>(array: T[]): T | undefined {
return array[0];
}
const numbers = firstElement([1, 2, 3]); // 型: number
const strings = firstElement(["a", "b"]); // 型: string
// ジェネリックインターフェース
interface ApiResponse<T> {
data: T;
success: boolean;
message?: string;
timestamp: Date;
}
interface User {
id: string;
name: string;
email: string;
}
async function getUser(id: string): Promise<ApiResponse<User>> {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
```
## ユーティリティ型
```typescript
interface Product {
id: string;
name: string;
price: number;
description: string;
stock: number;
createdAt: Date;
}
// Partial - すべてのプロパティをオプショナルに
type ProductUpdate = Partial<Product>;
// Pick - 特定のプロパティのみ
type ProductPreview = Pick<Product, "id" | "name" | "price">;
// Omit - 特定のプロパティを除外
type NewProduct = Omit<Product, "id" | "createdAt">;
// Required - すべてのプロパティを必須に
type CompleteProduct = Required<Product>;
// Readonly - すべてのプロパティを読み取り専用に
type ImmutableProduct = Readonly<Product>;
```
## 条件型
```typescript
// 単純な条件型
type IsString<T> = T extends string ? true : false;
type Test1 = IsString<string>; // true
type Test2 = IsString<number>; // false
// 配列要素型の抽出
type ArrayElement<T> = T extends (infer E)[] ? E : never;
type NumberElement = ArrayElement<number[]>; // number
// 関数戻り値型の抽出
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
```
## 型ガード
```typescript
interface Dog {
type: "dog";
bark: () => void;
}
interface Cat {
type: "cat";
meow: () => void;
}
type Pet = Dog | Cat;
// 型ガード関数
function isDog(pet: Pet): pet is Dog {
return pet.type === "dog";
}
function petSound(pet: Pet) {
if (isDog(pet)) {
pet.bark(); // TypeScriptはpetがDogであることを認識
} else {
pet.meow(); // TypeScriptはpetがCatであることを認識
}
}
```
## マップ型
```typescript
interface Form {
username: string;
email: string;
password: string;
}
// すべてのフィールドをnullableに
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
type NullableForm = Nullable<Form>;
// ゲッター関数付きフィールド
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type FormGetters = Getters<Form>;
// { getUsername: () => string; getEmail: () => string; ... }
```
このガイドは日本語開発者がTypeScriptの型システムを完全に理解するのに役立ちます。This typescript prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their typescript implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For typescript projects, consider mentioning your framework version, coding style, and any specific libraries you're using.