TypeScriptをより効率的に使うためのちょっとしたテクニック集です
type Status = "loading" | "success" | "error";
function handleStatus(status: Status) {
switch (status) {
case "loading":
return "読み込み中...";
case "success":
return "成功しました!";
case "error":
return "エラーが発生しました";
}
}
型安全性を保ちながら、わかりやすいコードが書けます
const user = {
profile: {
name: "太郎",
address: {
city: "東京"
}
}
};
// 安全にネストされたプロパティにアクセス
const city = user.profile?.address?.city;
?. を使うことで、undefined や null チェックが簡潔に書けます
type Color = "red" | "green" | "blue";
type Size = "small" | "medium" | "large";
type ClassName = `${Color}-${Size}`;
// "red-small" | "red-medium" | ... | "blue-large"
文字列リテラル型を組み合わせて、強力な型定義ができます
TypeScriptの型システムを活用して、より安全で読みやすいコードを書きましょう!