What are Logical operators in TypeScript? how to use Logical operators in TypeScript? With examples.

Опубликовано: 30 Сентябрь 2024
на канале: TypeScript Insights
190
3

TypeScript supports several logical operators that are used to perform logical operations on Boolean values. These operators are similar to those in JavaScript. Here are the logical operators in TypeScript:

1. Logical AND (&&): This operator returns `true` if both operands are `true`, otherwise, it returns `false`.

```typescript
const a: boolean = true;
const b: boolean = false;

const result1: boolean = a && b; // false
const result2: boolean = a && true; // true
```

2. Logical OR (||): This operator returns `true` if at least one of the operands is `true`. If both operands are `false`, it returns `false`.

```typescript
const a: boolean = true;
const b: boolean = false;

const result1: boolean = a || b; // true
const result2: boolean = false || false; // false
```

3. Logical NOT (!): This is a unary operator that returns the opposite Boolean value of the operand.

```typescript #ziakhan #saylani #piaic
const a: boolean = true;
const b: boolean = false;

const result1: boolean = !a; // false
const result2: boolean = !b; // true
```

These logical operators can be used to create complex conditions and control the flow of your TypeScript code based on the evaluation of these conditions. Keep in mind that the operands of logical operators must be of type `boolean`, otherwise, TypeScript will raise a type error.