乐闻世界logo
搜索文章和话题

How will you check if a variable is null or undefined in TypeScript?

1个答案

1

In TypeScript, checking if a variable is null or undefined can be achieved through several methods. Below are several common approaches:

1. Using == null for Checking

In JavaScript and TypeScript, the double equality operator == can check if a variable is null or undefined because null == undefined evaluates to true in JavaScript. This method is straightforward and intuitive.

typescript
function isNullOrUndefined(value: any): boolean { return value == null; } const a: any = null; const b: any = undefined; const c: any = 5; console.log(isNullOrUndefined(a)); // Output: true console.log(isNullOrUndefined(b)); // Output: true console.log(isNullOrUndefined(c)); // Output: false

2. Using Strict Equality === for Checking

To explicitly check for null and undefined separately, use the strict equality operator ===. This method strictly differentiates between null and undefined without type coercion.

typescript
function isNull(value: any): boolean { return value === null; } function isUndefined(value: any): boolean { return value === undefined; } const a: any = null; const b: any = undefined; const c: any = 5; console.log(isNull(a)); // Output: true console.log(isNull(b)); // Output: false console.log(isUndefined(b)); // Output: true console.log(isUndefined(c)); // Output: false

3. Using Logical OR Operator || for Default Values

Sometimes, in addition to checking if a variable is null or undefined, you may need to provide a default value. This can be achieved using the logical OR operator ||.

typescript
function getValueOrDefault(value: any, defaultValue: any): any { return value == null ? defaultValue : value; } const a: any = null; const b: any = undefined; const c: any = 5; console.log(getValueOrDefault(a, 10)); // Output: 10 console.log(getValueOrDefault(b, 10)); // Output: 10 console.log(getValueOrDefault(c, 10)); // Output: 5

4. Using Optional Chaining

TypeScript 3.7 introduced optional chaining, enabling safe access to deeply nested properties without explicit checks for null or undefined at each level.

typescript
type User = { name: string; address?: { street?: string; city?: string; }; }; function getAddress(user: User): string | undefined { return user.address?.street; } const userWithAddress: User = { name: "Alice", address: { street: "123 Main St" } }; const userWithoutAddress: User = { name: "Bob" }; console.log(getAddress(userWithAddress)); // Output: "123 Main St" console.log(getAddress(userWithoutAddress)); // Output: undefined

Each method has its own appropriate use case, and the choice depends on your specific requirements and context.

2024年7月29日 13:40 回复

你的答案