🐡
TypeScriptの交差型
TypeScriptの型レベルコードについてあまり慣れてないので勉強を始めた。
以下のコードのItemForm
がどういう型を持つのか。
type Item = {
id: string;
title: string;
body: string;
};
type ItemForm = Item & {
edit: boolean;
};
&
はintersection type(交差型)という。
Intersection types are closely related to union types, but they are used very differently. An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable is a type which is all of Person and Serializable and Loggable. That means an object of this type will have all members of all three types.
intersection typeは異なるtype同士を一緒くたにするもの。というわけで、ItemForm
は以下の4つのプロパティを全て持つ必要がある。
id
title
body
edit
interfaceでは&
の部分をextendsとすることで同様の、typeの拡張が行える。
interface Item {
id: string;
title: string;
body: string;
};
interface ItemForm extends Item {
edit: boolean;
};
vertical barを使った場合
type Item = {
id: string;
title: string;
body: string;
};
type ItemForm = Item | {
edit: boolean;
};
|
はunion type(合併型)で、両方の型か一方の型のプロパティを全て使う。
参考
Discussion