专业人士使用的 7 个 TypeScript 秘密技巧😎🤫 使用的资源 感谢阅读

2025-05-27

专业人士使用的 7 个 TypeScript 秘密技巧😎🤫

使用的资源

感谢阅读

TypeScript是一款出色的工具,可以让我们的生活更轻松并避免错误,但有时使用起来会让人感到不知所措。

压倒

本文概述了所有专业人士使用的 7 个TypeScript技巧,它们将使您的生活更轻松。

1. 类型推断

当你帮助Typescript缩小数据类型时,它足够智能,可以推断数据类型。

enum CounterActionType {
  Increment = "INCREMENT",
  IncrementBy = "INCREMENT_BY",
}

interface IncrementAction {
  type: CounterActionType.Increment;
}

interface IncrementByAction {
  type: CounterActionType.IncrementBy;
  payload: number;
}

type CounterAction =
  | IncrementAction
  | IncrementByAction;

function reducer(state: number, action: CounterAction) {
  switch (action.type) {
    case CounterActionType.Increment:
      // TS infers that the action is IncrementAction
      // & has no payload
      return state + 1;
    case CounterActionType.IncrementBy:
      // TS infers that the action is IncrementByAction
      // & has a number as a payload
      return state + action.payload;
    default:
      return state;
  }
}
Enter fullscreen mode Exit fullscreen mode

如上所示,TypeScript根据属性推断操作的类型type,因此您不需要检查是否payload存在。

2. 文字类型

通常您需要为变量提供特定的值,这时文字类型就派上用场了。

type Status = "idle" | "loading" | "success" | "error";
Enter fullscreen mode Exit fullscreen mode

它也适用于数字:

type Review = 1 | 2 | 3 | 4 | 5;

// or better yet:
const reviewMap = {
  terrible: 1,
  average: 2,
  good: 3,
  great: 4,
  incredible: 5,
} as const;

// This will generate the same type as above,
// but it's much more maintainable
type Review = typeof reviewMap[keyof typeof reviewMap];
Enter fullscreen mode Exit fullscreen mode

3. 类型保护

类型保护是缩小变量类型的另一种方法:

function isNumber(value: any): value is number {
  return typeof value === "number";
}

const validateAge = (age: any) => {
  if (isNumber(age)) {
    // validation logic
    // ...
  } else {
    console.error("The age must be a number");
  }
};
Enter fullscreen mode Exit fullscreen mode

注意:在上面的例子中,最好使用:

const validateAge = (age: number) => {
  // ...
};
Enter fullscreen mode Exit fullscreen mode

该示例经过简化,以展示类型保护如何工作。

4. 索引签名

当对象中动态键时,可以使用索引签名来定义其类型:

enum PaticipationStatus {
  Joined = "JOINED",
  Left = "LEFT",
  Pending = "PENDING",
}

interface ParticipantData {
  [id: string]: PaticipationStatus;
}

const participants: ParticipantData = {
  id1: PaticipationStatus.Joined,
  id2: PaticipationStatus.Left,
  id3: PaticipationStatus.Pending,
  // ...
};
Enter fullscreen mode Exit fullscreen mode

5. 泛型

泛型是增强代码复用性的强大工具。它允许你定义一个由函数用途决定的类型

在下面的例子中,T是一个泛型类型:

const clone = <T>(object: T) => {
  const clonedObject: T = JSON.parse(JSON.stringify(object));
  return clonedObject;
};

const obj = {
  a: 1,
  b: {
    c: 3,
  },
};

const obj2 = clone(obj);
Enter fullscreen mode Exit fullscreen mode

6. 不可变类型

您可以通过添加来使类型不可变as const。这可以确保您不会意外更改值。

const ErrorMessages = {
  InvalidEmail: "Invalid email",
  InvalidPassword: "Invalid password",
  // ...
} as const;

// This will throw an error
ErrorMessages.InvalidEmail = "New error message";
Enter fullscreen mode Exit fullscreen mode

7. 部分、挑选、省略和必需类型

通常在处理服务器本地数据时,您需要使某些属性成为可选必需的

无需定义数百个包含相同数据且版本略有不同接口。您可以使用PartialPickOmit&Required类型来实现。

interface User {
  name: string;
  age?: number;
  email: string;
}

type PartialUser = Partial<User>;
type PickUser = Pick<User, "name" | "age">;
type OmitUser = Omit<User, "age">;
type RequiredUser = Required<User>;

// PartialUser is equivalent to:
// interface PartialUser {
//   name?: string;
//   age?: number;
//   email?: string;
// }

// PickUser is equivalent to:
// interface PickUser {
//   name: string;
//   age?: number;
// }

// OmitUser is equivalent to:
// interface OmitUser {
//   name: string;
//   email: string;
// }

// RequiredUser is equivalent to:
// interface RequiredUser {
//   name: string;
//   age: number;
//   email: string;
// }
Enter fullscreen mode Exit fullscreen mode

当然,您可以使用交集来组合它们:

type A = B & C;
Enter fullscreen mode Exit fullscreen mode

其中B&C为任意类型。

就这些啦,朋友们!🎉

使用的资源

  1. Freepik
  2. Giphy

感谢阅读

需要一位顶级软件开发自由职业者来解决你的开发难题吗?在Upwork上联系我

想看看我正在做什么吗?查看我的个人网站GitHub

想联系我吗?请在LinkedIn上联系我

关注我的博客,每两周Medium上获取最新资讯

常问问题

这些是我经常收到的一些问题。希望这个常见问题解答部分能解决您的问题。

  1. 我是初学者,该如何学习前端 Web 开发?
    可以参考以下文章:

    1. 前端流行语
    2. 前端开发路线图
    3. 前端项目构想
    4. 从初学者过渡到中级前端开发人员
  2. 你能指导我吗?

    抱歉,我工作已经很忙了,没时间指导任何人。

文章来源:https://dev.to/ruppysuppy/7-secret-typescript-tricks-pros-use-3ckg
PREV
每个 JavaScript 开发者都应该知道的 7 个速记优化技巧 😎 感谢阅读
NEXT
你可能不知道的 7 个 JS 巧妙技巧,感谢阅读