読み込み中...
基本的な型
実践コード
// Union型
type Status = 'pending' | 'success' | 'error';
// Intersection型
type User = { name: string } & { age: number };
// タプル型
type Point = [number, number];// 基本的なジェネリクス
function identity<T>(value: T): T {
return value;
}
// 配列のジェネリクス
function getFirst<T>(arr: T[]): T | undefined {
return arr[0];
}
// 制約付きジェネリクス
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}学んだこと:
extends keyofで型安全なプロパティアクセスtype User = {
id: string;
name: string;
email: string;
};
// すべてオプショナル
type PartialUser = Partial<User>;
// すべて必須
type RequiredUser = Required<User>;// 特定のプロパティだけ抽出
type UserBasic = Pick<User, 'id' | 'name'>;
// 特定のプロパティを除外
type UserWithoutEmail = Omit<User, 'email'>;// キーと値の型を指定
type UserRole = Record<string, 'admin' | 'user' | 'guest'>;
const roles: UserRole = {
'user1': 'admin',
'user2': 'user',
};実務での活用例:
Partial を使用Pick で必要な項目だけ抽出Record を使用// T が string なら true、それ以外なら false
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false// 関数の戻り値の型を取得
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: '1', name: 'Suzuki' };
}
type User = ReturnType<typeof getUser>;
// { id: string; name: string; }// すべてのプロパティを readonly に
type Readonly<T> = {
readonly [K in keyof T]: T[K];
};
// すべてのプロパティをオプショナルに
type Partial<T> = {
[K in keyof T]?: T[K];
};難しかった点:
infer の使い方が最初は理解できなかった// ベースとなるエンティティ型
type Entity = {
id: string;
createdAt: Date;
updatedAt: Date;
};
// リポジトリインターフェース
interface IRepository<T extends Entity> {
findById(id: string): Promise<T | null>;
findAll(): Promise<T[]>;
create(data: Omit<T, 'id' | 'createdAt' | 'updatedAt'>): Promise<T>;
update(id: string, data: Partial<Omit<T, 'id' | 'createdAt' | 'updatedAt'>>): Promise<T>;
delete(id: string): Promise<void>;
}
// ユーザーエンティティ
type User = Entity & {
name: string;
email: string;
};
// ユーザーリポジトリ
class UserRepository implements IRepository<User> {
async findById(id: string): Promise<User | null> {
// 実装
}
// ... 他のメソッド
}メリット:
Omitで自動生成されるフィールドを除外Partialで部分更新を型安全にconst config = {
apiUrl: 'https://api.example.com',
timeout: 3000,
} as const;
type ConfigKey = keyof typeof config; // 'apiUrl' | 'timeout'const colors = ['red', 'green', 'blue'] as const;
type Color = typeof colors[number]; // 'red' | 'green' | 'blue'const config = {
apiUrl: 'https://api.example.com',
timeout: 3000,
} satisfies Record<string, string | number>;タグ: @学習 @TypeScript @プログラミング @記録
コメント