👀
インターセクション型【個人学習まとめ】
インターセクション型
組み合わされたすべての型の特性を持つ。記法としては「AかつB」の型だと考えるとよい。
type MultiType = TypeA & TypeB & TypeC;
//ダミー
type TypeA = {
type_a: string
}
type TypeB = {
type_b: number
}
type TypeC = {
type_c: boolean
}
Cpu型とMemory型の2つの型をインターセクション型を使って結合して、Pc型を作成。
Pc型は、Cpu型とMemory型の両方がもつプロパティを含む必要がある。
type Cpu = {
cpu: string
core: number
}
type Memory = {
memorySize: number;
}
type PcType = Cpu & Memory;
const myPc: PcType = {
cpu: 'intel',
core: 8,
memorySize: 16
}
片方の型を持つプロパティが指定されていなければエラー。
const friendPc: PcType = {
cpu: 'intel',
core: 8,
}

VSCodeの候補にPcType型が表示される
console.log(`cpu: ${myPc.cpu} core: ${myPc.core} memory: ${myPc.core}`);// cpu: intel core: 8 memory: 16

Discussion