类提供名义类型,而对象类型提供结构类型。
假设我想引入带有x 和y 字段的Vector 类型。当我去创建我的 add(p: Point, v: Vector): Point 函数时,结构类型被证明是不够的,例如
type Point = {x: number, y: number};
type Vector = {x: number, y: number};
function add(p: Point, v: Vector): Point {
return {x: p.x + v.x, y: p.y + v.y};
}
const p1: Point = {x:0, y:5};
const p2: Point = {x:2, y:3};
const v: Vector = add(p1, p2); // This is not an error in Flow
将其与带有类的名义类型版本进行对比:
class Point { x: number; y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
class Vector { x: number; y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
function add(p: Point, v: Vector): Point {
return new Point(p.x + v.x, p.y + v.y);
}
const p1: Point = new Point(0, 5);
const p2: Point = new Point(2, 3);
const v: Vector = add(p1, p2); // Error: p2 isn't a Vector
(实际上,您可能会将 add 作为方法附加到点类上,但我已将其与对象类型示例分开以用于并行结构。)
请注意,您可以使用标签字段从对象类型中获得一些名义类型的表象,例如
type Point = { tag: "point", x: number y: number };
type Vector = { tag: "vector", x: number, y: number };
如果你的类没有任何方法,那么我建议这是要走的路。