TypeScript 中条件逻辑的最佳实践

TypeScript 中条件逻辑的最佳实践

本文解释了在 TypeScript 中使用条件逻辑的最佳实践。

YouTube Video

TypeScript 中条件逻辑的最佳实践

使用类型保护缩小类型范围

通过利用 TypeScript 的类型系统并在 if 语句中使用类型保护,可以提高类型安全性和可读性。

1function processInput(input: string | number) {
2    if (typeof input === "string") {
3        console.log(`String input: ${input.toUpperCase()}`);
4    } else {
5        console.log(`Number input: ${input.toFixed(2)}`);
6    }
7}

使用 typeof 和其他类型保护可确保每个代码块中的代码是类型安全且符合上下文的。

避免嵌套的 if 语句

深度嵌套的 if 语句会降低代码的可读性和可维护性。可以改用提前返回、逻辑运算符或提取函数。

不推荐的示例:

1function checkUser(user: { age?: number; isAdmin?: boolean }) {
2    if (user.age) {
3        if (user.age > 18) {
4            if (user.isAdmin) {
5                console.log("User is an adult admin.");
6            }
7        }
8    }
9}

改进的示例:

1function checkUser(user: { age?: number; isAdmin?: boolean }) {
2    if (!user.age || user.age <= 18 || !user.isAdmin) {
3        return;
4    }
5    console.log("User is an adult admin.");
6}

这种方法简化了代码,使逻辑更易理解。

利用可选链操作符

在检查嵌套属性时,使用可选链操作符 (?.) 来避免不必要的 if 条件。

未使用可选链操作符:

1if (user && user.profile && user.profile.email) {
2    console.log(user.profile.email);
3}

使用可选链操作符:

1if (user?.profile?.email) {
2    console.log(user.profile.email);
3}

这减少了样板代码并提高了可读性。此处的样板代码是指为完成特定编程任务而经常需要的重复性标准代码。

使用严格相等运算符

TypeScript 支持严格类型,使用严格相等运算符 (===) 或严格不等运算符 (!==) 有助于防止意外的类型转换。

不推荐的示例:

1if (value == "123") {
2    console.log("Value is 123.");
3}

改进的示例:

1if (value === "123") {
2    console.log("Value is 123.");
3}

为明确条件使用枚举或字面量类型

使用枚举或字面量类型可以明确条件并减少错误的可能性。

 1type Status = "success" | "error" | "loading";
 2
 3function displayMessage(status: Status) {
 4    if (status === "success") {
 5        console.log("Operation succeeded.");
 6    } else if (status === "error") {
 7        console.log("Operation failed.");
 8    } else {
 9        console.log("Loading...");
10    }
11}

通过定义预期值,TypeScript 可以检测类型并确保准确性。

合并相似条件

当多个条件共享相同逻辑时,可以使用逻辑运算符或 switch 语句将它们合并。

不推荐的示例:

1if (role === "admin") {
2    grantAccess();
3}
4if (role === "superadmin") {
5    grantAccess();
6}

改进的示例:

1if (role === "admin" || role === "superadmin") {
2    grantAccess();
3}

或者,可以使用 switch 语句来处理多个清晰的分支:

 1switch (role) {
 2    case "admin":
 3    case "superadmin":
 4        grantAccess();
 5        break;
 6    case "user":
 7        console.log("Limited access.");
 8        break;
 9    default:
10        console.log("No access.");
11}

避免让条件表达式变得复杂

if 语句中的复杂条件表达式会降低可读性。将它们提取为有意义的变量或函数。

不推荐的示例:

1if (user.age > 18 && user.isAdmin && user.permissions.includes("write")) {
2    console.log("User can write.");
3}

改进的示例:

1const isAdultAdminWithWriteAccess =
2    user.age > 18 && user.isAdmin && user.permissions.includes("write");
3
4if (isAdultAdminWithWriteAccess) {
5    console.log("User can write.");
6}

为条件命名可以提高代码的清晰度并使其具备自解释性。

对简单条件使用三元运算符

对于简单条件,使用三元运算符可以使代码更加简洁。

示例:

1const message = isLoggedIn ? "Welcome back!" : "Please log in.";
2console.log(message);

然而,避免将三元运算符用于复杂条件,因为这会降低可读性。

用数组或映射替换条件分支

当条件只是一个值的映射时,相比于 switch 语句或复杂的 if-else 块,使用数组或映射可以提高代码的可读性和可维护性。在 TypeScript 中,您可以利用类型信息来更安全地实现它。

不推荐的示例:

 1function getDayName(day: number): string {
 2    switch (day) {
 3        case 0:
 4            return "Sunday";
 5        case 1:
 6            return "Monday";
 7        case 2:
 8            return "Tuesday";
 9        case 3:
10            return "Wednesday";
11        case 4:
12            return "Thursday";
13        case 5:
14            return "Friday";
15        case 6:
16            return "Saturday";
17        default:
18            return "Invalid day";
19    }
20}

改进示例:使用数组

 1function getDayName(day: number): string {
 2    const days = [
 3        "Sunday",
 4        "Monday",
 5        "Tuesday",
 6        "Wednesday",
 7        "Thursday",
 8        "Friday",
 9        "Saturday"
10    ];
11    return days[day] ?? "Invalid day";
12}

改进示例:使用映射

 1function getDayName(day: number): string {
 2    const dayMap = new Map<number, string>([
 3        [0, "Sunday"],
 4        [1, "Monday"],
 5        [2, "Tuesday"],
 6        [3, "Wednesday"],
 7        [4, "Thursday"],
 8        [5, "Friday"],
 9        [6, "Saturday"]
10    ]);
11    return dayMap.get(day) ?? "Invalid day";
12}

结论

通过遵循这些最佳实践,您可以使 TypeScript 中的 if 语句清晰、高效且易于维护。通过使用 TypeScript 的功能,例如类型保护、可选链以及枚举,可以提高代码的可读性和健壮性。通过遵循最佳实践,可以使条件简洁明了,从而使代码更易于理解和维护。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video