什么是可辨识联合类型
在 TypeScript 中,我们可以使用联合类型来表示一个值可能是多个类型中的任意一种。例如:
type MyType = string | number | boolean;
但是,在某些情况下,我们需要根据联合类型中的某个属性来确定它的具体类型,这就是可辨识联合类型。例如:
// www.javascriptcn.com code example
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Square | Rectangle;在上面的例子中,我们定义了两个接口 Square 和 Rectangle,它们都有一个属性 kind,用于区分不同的形状。然后,我们使用联合类型 Shape 来表示这两种形状。这样,当我们使用 Shape 类型的变量时,就可以根据它的 kind 属性来确定它的具体类型。
如何处理可辨识联合类型
在 TypeScript 中,我们可以使用 switch 语句来处理可辨识联合类型。例如:
function area(shape: Shape) {
switch (shape.kind) {
case "square":
return shape.size * shape.size;
case "rectangle":
return shape.width * shape.height;
}
}在上面的例子中,我们定义了一个函数 area,它接受一个 Shape 类型的参数。然后,我们使用 switch 语句来根据 shape.kind 属性来确定具体的形状,并计算它的面积。
需要注意的是,当我们使用 switch 语句处理可辨识联合类型时,必须包含所有可能的情况。如果漏掉了某种情况,TypeScript 就会给出一个编译错误。例如:
function area(shape: Shape) {
switch (shape.kind) {
case "square":
return shape.size * shape.size;
}
}上面的代码会报错,因为我们漏掉了处理 Rectangle 的情况。
示例代码
下面是一个完整的示例代码,用于演示如何处理可辨识联合类型:
// www.javascriptcn.com code example
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Square | Rectangle;
function area(shape: Shape) {
switch (shape.kind) {
case "square":
return shape.size * shape.size;
case "rectangle":
return shape.width * shape.height;
}
}
const square: Square = { kind: "square", size: 10 };
const rectangle: Rectangle = { kind: "rectangle", width: 10, height: 20 };
console.log(area(square)); // 输出 100
console.log(area(rectangle)); // 输出 200在上面的代码中,我们定义了两个接口 Square 和 Rectangle,它们都有一个属性 kind,用于区分不同的形状。然后,我们使用联合类型 Shape 来表示这两种形状。接着,我们定义了一个函数 area,它接受一个 Shape 类型的参数,并使用 switch 语句来根据 shape.kind 属性来确定具体的形状,并计算它的面积。最后,我们定义了两个变量 square 和 rectangle,分别表示一个正方形和一个矩形,并分别调用了 area 函数来计算它们的面积。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67da3afaa941bf713420b9b6