首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Typescript中使用布尔值区分联合

在 TypeScript 中,使用布尔值来区分联合类型是一种常见的模式,通常称为“标签联合”或“判别联合”。这种模式通过在每个联合成员中添加一个共同的布尔属性来区分不同的类型。

示例

假设我们有一个联合类型 Shape,它可以是 CircleSquare。我们可以使用一个布尔属性 isCircle 来区分这两种类型。

定义联合类型

代码语言:javascript
复制
interface Circle {
    isCircle: true;
    radius: number;
}

interface Square {
    isCircle: false;
    sideLength: number;
}

type Shape = Circle | Square;

在这个例子中,CircleSquare 都有一个共同的布尔属性 isCircle,但它们的值不同:CircleisCircletrue,而 SquareisCirclefalse

使用联合类型

我们可以使用类型保护来区分联合类型的不同成员:

代码语言:javascript
复制
function getArea(shape: Shape): number {
    if (shape.isCircle) {
        // TypeScript 知道 shape 是 Circle
        return Math.PI * shape.radius * shape.radius;
    } else {
        // TypeScript 知道 shape 是 Square
        return shape.sideLength * shape.sideLength;
    }
}

// 示例用法
const myCircle: Circle = { isCircle: true, radius: 5 };
const mySquare: Square = { isCircle: false, sideLength: 10 };

console.log(getArea(myCircle)); // 输出: 78.53981633974483
console.log(getArea(mySquare)); // 输出: 100

解释

  1. 定义联合类型
    • CircleSquare 接口都有一个共同的布尔属性 isCircle
    • Shape 类型是 CircleSquare 的联合类型。
  2. 类型保护
    • getArea 函数中,我们使用 if (shape.isCircle) 来检查 isCircle 属性。
    • TypeScript 会根据 isCircle 的值自动推断 shape 的具体类型。
    • 如果 isCircletrue,TypeScript 知道 shapeCircle 类型。
    • 如果 isCirclefalse,TypeScript 知道 shapeSquare 类型。

其他示例

你也可以使用其他布尔属性来区分联合类型。例如,假设我们有一个联合类型 Vehicle,它可以是 CarBike,我们可以使用布尔属性 isCar 来区分这两种类型:

代码语言:javascript
复制
interface Car {
    isCar: true;
    numberOfDoors: number;
}

interface Bike {
    isCar: false;
    hasPedals: boolean;
}

type Vehicle = Car | Bike;

function describeVehicle(vehicle: Vehicle): string {
    if (vehicle.isCar) {
        return `This car has ${vehicle.numberOfDoors} doors.`;
    } else {
        return `This bike ${vehicle.hasPedals ? 'has' : 'does not have'} pedals.`;
    }
}

// 示例用法
const myCar: Car = { isCar: true, numberOfDoors: 4 };
const myBike: Bike = { isCar: false, hasPedals: true };

console.log(describeVehicle(myCar)); // 输出: This car has 4 doors.
console.log(describeVehicle(myBike)); // 输出: This bike has pedals.

通过这种方式,你可以在 TypeScript 中使用布尔值来区分联合类型,并利用类型保护来处理不同的类型。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

【TypeScript 演化史 — 第一章】non-nullable 的类型

在这篇文章中,我们将讨论发布于 TypeScript 2.0 中的 non-nullable 类型,这是对类型系统的一个重大的改进,该特性可对 null 和 undefined 的检查。cannot read property 'x' of undefined 和 undefined is not a function 在 JS 中是非常常见的错误,non-nullable 类型可以避免此类错误。 null 和 undefined 的值 在 TypeScript 2.0 之前,类型检查器认为 null 和 undefined 是每种类型的有效值。基本上,null 和 undefined 可以赋值给任何东西。这包括基本类型,如字符串、数字和布尔值: let name: string; name = "Marius"; // OK name = null; // OK name = undefined; // OK let age: number; age = 24; // OK age = null; // OK age = undefined; // OK let isMarried: boolean; isMarried = true; // OK isMarried = false; // OK isMarried = null; // OK isMarried = undefined; // OK 以 number 类型为例。它的域不仅包括所有的IEEE 754浮点数,而且还包括两个特殊的值 null 和 undefined 对象、数组和函数类型也是如此。无法通过类型系统表示某个特定变量是不可空的。幸运的是,TypeScript 2.0 解决了这个问题。 严格的Null检查 TypeScript 2.0 增加了对 non-nullable 类型的支持,并新增严格 null 检查模式,可以通过在命令行上使用 ——strictNullChecks 标志来选择进入该模式。或者,可以在项目中的 tsconfig.json 文件启用 strictnullcheck 启用。 { "compilerOptions": { "strictNullChecks": true // ... } } 在严格的 null 检查模式中,null 和 undefined 不再分配给每个类型。null 和undefined 现在都有自己的类型,每个类型只有一个值

02
领券