TypeScript の型エイリアス (type)
型エイリアスは、型に名前を付けるものです。新しい型を作成するわけではなく、単に既存の型に対して、より短く、より意味のある名前を付けるだけです。
1. 型エイリアスの基本的な構文
(1) 命名の種類
TYPESCRIPT
type ID = number;
type Name = string;
type Active = boolean;
let userId: ID = 42;
let userName: Name = "Charlie";
let isActive: Active = true;
(2) オブジェクト型の別名
TYPESCRIPT
type User = {
name: string;
age: number;
email: string;
};
let user: User = {
name: "Charlie",
age: 20,
email: "xiaoming@example.com"
};
💡
type も interface も、オブジェクトの構造を定義することができます— 構文は若干異なります(type では =, while interface を使用しますが、interface では使用しません)が、その効果はほぼ同じです。
(3) 関数型の別名
TYPESCRIPT
type GreetFunction = (name: string) => string;
let greet: GreetFunction = (name) => `Hello,${name}!`;
console.log(greet("Charlie")); // "Hello,Charlie!"
2. ユニオン型の別名
type 最も一般的な用途は、ユニオン型の命名です。これにより、コードの可読性が大幅に向上します:
(1) 文字列の連結
TYPESCRIPT
type Status = "pending" | "active" | "completed" | "cancelled";
type Role = "admin" | "editor" | "viewer";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
let orderStatus: Status = "pending";
let userRole: Role = "admin";
let method: HttpMethod = "GET";
(2) デジタル・コンバージェンス
TYPESCRIPT
type HttpStatus = 200 | 301 | 400 | 404 | 500;
type Bit = 0 | 1;
let code: HttpStatus = 200;
let flag: Bit = 1;
(3) ハイブリッド型
TYPESCRIPT
type Result = string | Error;
type Id = number | string | undefined;
let output: Result = "Success";
output = new Error("Failure"); // ✅ That's also legal
▶ 例:型エイリアスを使用したAPIレスポンスの記述
TYPESCRIPT
type ApiResponse<T> = {
status: number;
message: string;
data: T;
};
type User = {
id: number;
name: string;
email: string;
};
type UserResponse = ApiResponse<User>;
let response: UserResponse = {
status: 200,
message: "Achieve Success",
data: { id: 1, name: "Charlie", email: "xiao@example.com" }
};
console.log(`Status:${response.status}`);
console.log(`User:${response.data.name}`);
出力:
TEXT
Status:200
User:Charlie
3. クロスタイプのエイリアス
「交差型」では、& を使用して複数の型を 1 つの型に統合します。この新しい型は、元の各型のすべての特性を備えています:
(1) 基本的な構文
TYPESCRIPT
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
let person: Person = {
name: "Charlie",
age: 20
// Both must be present name and age
};
(2) 実践的な応用――複合スキル
TYPESCRIPT
type HasId = { id: number };
type Timestamped = { createdAt: Date; updatedAt: Date };
type SoftDeletable = { deletedAt: Date | null };
type Entity = HasId & Timestamped & SoftDeletable;
let article: Entity = {
id: 1,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null
};
(3) 相互の対立
2つの型に同じ名前のプロパティがあるものの、型が異なる場合、その共通部分の結果は never となります:
TYPESCRIPT
type A = { value: string };
type B = { value: number };
type C = A & B;
// C 's value The type is string & number = never
// No value can be both string and number
let c: C = { value: "" }; // ❌ You cannot string Assigned never
4. タプル型のエイリアス
TYPESCRIPT
type Point = [x: number, y: number];
type KeyValuePair = [key: string, value: number];
type RGB = [red: number, green: number, blue: number];
let coord: Point = [10, 20];
let entry: KeyValuePair = ["score", 95];
let color: RGB = [255, 128, 0];
// Deconstruction
let [x, y] = coord;
let [key, val] = entry;
5. テンプレートリテラル型
TypeScript 4.1 では、テンプレートリテラル型が導入されました。これは、型レベルでの文字列連結です:
(1) 基本的な構文
TYPESCRIPT
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// Results:"onClick" | "onFocus" | "onBlur"
type CSSProperty = "margin" | "padding";
type CSSDirection = "top" | "right" | "bottom" | "left";
type CSSRule = `${CSSProperty}-${CSSDirection}`;
// Results:"margin-top" | "margin-right" | ... | "padding-left"
(2) 組み込みの文字列演算型
| タイプ | 機能 | 例 |
|---|---|---|
Uppercase<S> |
すべて大文字 | Uppercase<"hello"> → "HELLO" |
Lowercase<S> |
すべて小文字 | Lowercase<"HELLO"> → "hello" |
Capitalize<S> |
頭文字を大文字にする | Capitalize<"hello"> → "Hello" |
Uncapitalize<S> |
小文字の頭文字 | Uncapitalize<"Hello"> → "hello" |
▶ 例:型安全なイベントシステム
TYPESCRIPT
type EventType = "click" | "change" | "submit";
type HandlerName = `on${Capitalize<EventType>}`;
// "onClick" | "onChange" | "onSubmit"
interface EventHandlers {
onClick?: (x: number, y: number) => void;
onChange?: (value: string) => void;
onSubmit?: (data: FormData) => void;
}
// Usage——handler Type hints for names,I won't spell it wrong
let handlers: EventHandlers = {
onClick: (x, y) => console.log(`Click:(${x}, ${y})`),
onChange: (value) => console.log(`Value change:${value}`)
};
6. 型とインターフェースの包括的な比較
(1) 機能の比較
| 機能 | タイプ | インターフェース |
|---|---|---|
| オブジェクトタイプ | ✅ type T = { ... } |
✅ interface T { ... } |
| 複合タイプ | ✅ type T = A | B |
❌ |
| 十字型 | ✅ type T = A & B |
代わりに extends を使用 |
| 基本型の別名 | ✅ type T = string |
❌ |
| タプル型 | ✅ type T = [A, B] |
❌ |
| テンプレートリテラル | ✅ type T = \...`` |
❌ |
| ステートメントの結合 | ❌ | ✅ |
| クラスの実装 | ✅ | ✅ |
| 拡張 | 使用 & | ✅ extends |
| 計算済みプロパティのキー | ✅ [K in Keys] |
❌ |
(2) 戦略を選択する
TEXT
Required Features → Select
───────────────────────────────
Composite Types A | B → type
Aliases for Basic Types → type
Tuple [A, B] → type
Template Literal Types → type
Object Shape + Inheritance Required → interface
Object Shape + Statement Merger → interface
Simple Object Shapes → Either is fine,As long as the team is on the same page, that's fine.
❓ よくある質問
Q
type は extends を継承に使用できますか?A
type には extends の構文はありませんが、クロス型 &—type Child = Parent & { extra: string } を使用することで同様の効果を得ることができます。interfaceにおけるextends構文はより明確で、競合を検出できます。クロス型間で競合が発生した場合、エラーではなくneverが生成されます(その型は単に利用不可になるだけです)。Q
type は class によって実装できますか?A はい。
type がオブジェクト型(共用体やプリミティブ型などを除く)を定義している限り、class はそれを実装できます。class User implements UserType { ... } は完全に有効です。Q
interfaceの代わりにtypeを使用しなければならないのはどのような場合ですか?A 以下の3つのケースがあります:(1) ユニオン型――
interfaceではA | Bを表現できません; (2) タプル型—interface を使用することは可能ですが、非常に扱いにくい; (3) テンプレートリテラル型—interface はこれらをサポートしていません。それ以外のすべてのケースでは、両者は同等であり、どちらを使用しても構いません。Q テンプレートリテラル型の実際の用途は何ですか?
A 主に高度な型プログラミングに使用されます。例えば、イベント名(onClick/onFocus)の自動生成、CSSプロパティ(margin-top)の結合、ルーティングパスの型の推論などです。日常的な開発ではあまり使われませんが、フレームワークやライブラリの型を定義する際には非常に強力です。初心者は、その存在を知っておくだけで十分です。
📖 まとめ
- type: 既存の型にエイリアスを割り当てます。新しい型は作成しません。構文:
type Name = type - ユニオン型のエイリアスは、
typeの最も一般的な用途です。これにより、複雑なユニオン型を読みやすく、再利用可能にすることができます。 - クロス型
A & B:複数の型のすべての特性を組み合わせたもので、競合が生じた場合は結果は「never」となる - テンプレートリテラル型は、組み込み演算(Uppercaseなど)と組み合わせて、型レベルで文字列を連結します。
typeとinterfaceは、ほとんどの場合同等です。ただし、ユニオン型、タプル、およびテンプレートリテラルではtypeを使用する必要があります。
📝 練習問題
- 基本問題(難易度 ⭐):
typeを用いてStatusCode = 200 | 404 | 500を定義し、次にApiResponse<T> = { code: StatusCode; data: T }を定義してください。ApiResponse<string>のインスタンスを作成し、それを出力してください。 - 上級問題(難易度 ⭐⭐):クロス型の組み合わせ
HasId、HasTimestamps、HasAuditを使用して、完全なEntity型を定義してください。インスタンスオブジェクトを作成し、すべてのプロパティが満たされていることを確認してください。 - 課題(難易度:⭐⭐⭐):テンプレートリテラル型を使用して
CSSDirection = "top" | "right" | "bottom" | "left"を定義し、MarginStyle = { [K inmargin-${CSSDirection}]: number }を生成してください。生成された型に marginTop や marginRight などのプロパティが含まれていることを確認してください。



