5 个可以改善你的代码库的 TypeScript 功能

2025-06-05

5 个可以改善你的代码库的 TypeScript 功能

TypeScript 的出现改变了开发者处理 JavaScript 应用程序的方式。它不仅带来了类型安全的代码可靠性,还通过提供强大的重构功能和更智能的 JS 代码编写方式,提升了开发者的体验。

在这篇文章中,我想谈谈五个 TypeScript 功能,它们将改善您的代码库。

目录

1. 空值合并

让我们考虑下面的例子。

function getNumberOrDefault(value?: number) {
  return value || 22;
}
Enter fullscreen mode Exit fullscreen mode

在前面提到的例子中,如果传入的值未定义,我们希望返回一个默认值。然而,这段代码有一个严重的缺陷——JavaScript 会将其视为0一个falsy值。

console.log(getNumberOrDefault(10)) // Output 10
console.log(getNumberOrDefault(0)) // Output 22
Enter fullscreen mode Exit fullscreen mode

返回22可能不是我们期望这个函数会做的事情。由于空值合并,我们不需要重构代码并添加检查0,而是可以使用 的简写语法??

function getNumberOrDefaultTs(value?: number) {
    return value ?? 22;
}

console.log(getNumberOrDefault(10)) // Output 10
console.log(getNumberOrDefault(0)) // Output 0
Enter fullscreen mode Exit fullscreen mode

2. 类型保护

假设我们有两种类型TruckF1,它们扩展了同一个接口Car。虽然它们有一些共同的属性,但它们也分别拥有一组独特的属性,例如loadacceleration

interface Car {
  model: string;
}

interface Truck extends Car {
  load: number;
}

interface F1 extends Car {
  acceleration: number;
}

function scanCar(car: Truck | F1) {
    ...some code
}
Enter fullscreen mode Exit fullscreen mode

此外,我们有一个函数scanCar,它接受 aTruck或 aF1并执行一些特定类型的操作。

类型保护是一种让 TypeScript 知道我们当前正在处理哪种类型的好方法。

function carIsTruck(car: Truck | F1): car is Truck {
  return 'load' in car;
}

function scanCar(car: Truck | F1) {
  if(carIsTruck(car)) {
        // Only truck properties will be suggested
    console.log(`Truck has a load of ${car.load}`)
  } else {
        // Only F1 properties will be suggested
    console.log(`F1 has acceleration of ${car.acceleration}`)
  }
}
Enter fullscreen mode Exit fullscreen mode

类型保护是一个返回布尔值的函数,它通常用作条件语句的一部分,让 TypeScript 知道当前 if 块中假定的类型。

3. 枚举对象键

enum在某些情况下,我们希望强制对象键只能是某些特定的值。以下是使用和实现的方法Record

enum Size {
  M,
  L,
  XL
}

function getPlainTextSizes(): Record<Size, string> {
  return {
    [Size.M]: "medium",
    [Size.L]: "large",
    [Size.XL]: "extra large",
    10: "small", // error
    "size": "xs" // error
  }
}
Enter fullscreen mode Exit fullscreen mode

Record是一种通用类型 util,它允许定义键值映射的类型。

4. 通用接口

interface Item<T> {
  id: number,
  value: T,
}

interface Post {
  title: string;
}

const item1: Item<number> = { id: 1, value: 10 }
const item2: Item<Post> = { id: 1, value: { title: "Post name" } }
Enter fullscreen mode Exit fullscreen mode

TypeScript 中的泛型显著提高了代码的可重用性。

5. 泛型函数参数类型

interface Book {
  id: number;
  author: string;
}

interface Recipe {
  id: number;
  cookingTime: number;
}

function mapById<T extends { id: number }>(array: T[]): {[key: number]: T} {
  return array.reduce((map, item) => ({ ...map, [item.id]: item }), {})
}

const books: Book[] = [{ id: 1, author: "A" }];
const recipies: Recipe[] = [{ id: 1, cookingTime: 10 }];

mapById(books);
mapById(recipies);
Enter fullscreen mode Exit fullscreen mode

我们经常会遇到一些实用函数,它们只需要接口中的一些字段。在上面的例子中,你可以看到一个函数,它接受一个数组作为输入,并返回按 id 映射的值。唯一重要的是数组的项必须带有id。当你将参数传递给函数时,TypeScript 将会:

  1. 推断所提供参数的类型
  2. 检查参数是否符合指定条件(必须为id数字类型)所以现在您可以放心地将此帮助器用于各种接口。

概括

正如您所看到的,typescript 提供了许多工具来编写可重用且灵活的代码,而不会牺牲类型安全性。

感谢阅读!这篇文章尝试了一种新的格式,如果你觉得它有趣且有用,请告诉我。请帮忙传播,并在 Twitter 上关注我,获取更多关于 Web 开发的精彩内容!🚀

文章来源:https://dev.to/glebirovich/5-typescript-features-that-will-improve-your-codebase-hok
PREV
Typescript 数据结构:链表
NEXT
Guia Para Pessoas Desenvolvedoras Back-End 2021 - O que eu preciso saber?!