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

How to declare a type as nullable in TypeScript?

1个答案

1

In TypeScript, declaring a type as nullable is primarily achieved through union types, which involve the union of the type with null or undefined. This allows handling cases where values might be missing while maintaining type safety.

Basic Syntax

You can use | (pipe symbol) to combine a primitive type with null or undefined to declare a nullable type. For example:

typescript
let age: number | null; let name: string | undefined;

In this example, the variable age can be assigned a value of type number or null, while name can be a string or undefined.

Usage Example

Suppose you are developing an application where user profile information is retrieved from network requests. Network requests may fail for various reasons, such as network errors or data not found, in which case the user's age and name might not be defined.

typescript
interface UserProfile { name: string | undefined; age: number | null; } function fetchUserProfile(userId: string): UserProfile { // Simulate network request if (userId === "123") { return { name: "张三", age: 28 }; } else { // Simulate request failure return { name: undefined, age: null }; } } const userProfile = fetchUserProfile("123"); console.log(userProfile.name); // Output "张三" console.log(userProfile.age); // Output 28 const missingProfile = fetchUserProfile("unknown"); console.log(missingProfile.name); // Output undefined console.log(missingProfile.age); // Output null

In this example, we define a UserProfile interface where the name and age fields are nullable. This indicates that in actual applications, these fields may not have values (e.g., due to data not being loaded or request failures). By declaring types as nullable, TypeScript helps identify potential errors at compile time, such as attempting to access properties of null or undefined.

Summary

By using union types to combine primitive types with null or undefined, TypeScript provides a safe and effective way to handle optional or missing data. This approach not only enhances code robustness but also improves development efficiency, as most potential errors can be detected during compilation.

2024年8月2日 14:11 回复

你的答案