Intersection TypesとUnion Types
TypeScript
Intersection Types(交差型)
複数の型を1つにまとめることが出来るもの。
Type Alias
型に名前を付けることが出来るもの。
型が長くなって見づらくなってしまう時にType Aliasとして定義しておくことで
後ほどのコードの見通しが良くなる。
type Foo = {
a:number;
b:string;
}
const Test: Foo = {
a: 1,
b: "test",
}
Intersection Types
Intersection Types(交差型)は以下のように「&」でType Aliasを繋げることで
複数の型をまとめることが出来る。
type Foo = {
a:number;
b:string;
}
type Bar = {
c:boolean;
}
type FooBer = Foo & Bar;
const Test: FooBer = {
a: 1,
b: "",
c: true
}
Union Types(共用体型・合併型)
複数の型があった場合にどれか1つが成立すればOK。
「どちらか一方の型になる」という訳では無いので注意。
※もしそうであれば全ての型があった場合にエラーとなってしまうため。
Union Types(共用体型・合併型)は以下のように「|」でType Aliasを繋げることで
複数の型をまとめることが出来る。
type Foo = {
a:number;
b:string;
}
type Bar = {
c:boolean;
}
type FooBer = Foo | Bar;
const Test: FooBer = {
a: 1,
b: "",
c: true
}
Union Typesの絞り込み
以下のような場合に、例えばaをstringとして扱いたいとなった場合に、補完でnumberの方の補完も出てしまう等の
不都合が出てきてしまう。
type Foo = {
a:number;
b:string;
}
type Bar = {
a:string;
b:boolean;
}
type FooBer = Foo | Bar;
const Test: FooBer = {
a: 1,
b: "",
c: true
}
それを解決するために、以下のように「in演算子」を用いて解決することができる。
type Foo = {
a:number;
b:string;
}
type Bar = {
a:string;
b:boolean;
}
type FooBer = Foo | Bar;
const test: FooBer = {
a: 1,
b: "",
c: true
}
if("b" in test) {
test.a.〇〇〇
} else {
test.c.〇〇〇
}
testのbはstringなので、Fooの型だと推測ができる。