TypeScriptの便利なテクニック
TypeScriptはJavaScriptに型安全性を追加する素晴らしい言語です。今回は、日常的に使える便利なテクニックを紹介します。
型ガード
型ガードを使うと、条件分岐内で型を絞り込むことができます:
interface Dog {
bark(): void;
}
interface Cat {
meow(): void;
}
function isDog(animal: Dog | Cat): animal is Dog {
return (animal as Dog).bark !== undefined;
}
function makeSound(animal: Dog | Cat) {
if (isDog(animal)) {
animal.bark(); // TypeScriptはここでDog型と認識
} else {
animal.meow(); // ここではCat型と認識
}
}
ユーティリティ型
TypeScriptには便利なユーティリティ型が用意されています:
interface User {
id: number;
name: string;
email: string;
age: number;
}
// 全てのプロパティをオプショナルに
type PartialUser = Partial<User>;
// 特定のプロパティのみを選択
type UserBasic = Pick<User, 'id' | 'name'>;
// 特定のプロパティを除外
type UserWithoutEmail = Omit<User, 'email'>;
const assertion
as const を使うと、リテラル型として推論されます:
const colors = ['red', 'green', 'blue'] as const;
// type: readonly ["red", "green", "blue"]
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000,
} as const;
// 全てのプロパティがreadonly
まとめ
これらのテクニックを活用して、より型安全なコードを書いていきましょう!