構造的型システム
型の名前ではなく、その型が持つ「構造」が一致するかどうかで、型の互換性を判断する仕組み
中身(構造)が同じなら、名前が違っていても同じものとして扱える
構造的部分型 は構造的型システムの中で、具体的に「部分型」の関係をどのように決定するかというルールを指す
code:ts
interface Point {x: number; y: number;}
function printPoint(p: Point) {
console.log(座標: (${p.x}, ${p.y}));
}
// (1) Point 型として明示的に宣言したオブジェクト
const point1: Point = { x: 10, y: 20 };
printPoint(point1); // OK
// (2) Point 型とは宣言していないが、同じ構造を持つオブジェクト
const point2 = { x: 100, y: 200 };
printPoint(point2); // これもOK! TypeScriptは構造を見て互換性を判断する
// (3) 必要なプロパティに加え、余分なプロパティを持つオブジェクト
const point3 = { x: 1, y: 2, z: 3 };
printPoint(point3); // これもOK! 必要な x と y があれば良い
// (4) 構造が違うオブジェクト
const notAPoint = { name: "点A", value: 5 };
// printPoint(notAPoint); // これはエラー! x と y がないため互換性がない