3

秒懂 TypeScript 泛型工具类型!

 1 year ago
source link: https://www.fly63.com/article/detial/11767
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-06-20阅读量: 88标签: 泛型分享

扫一扫分享

如果你刚接触 TypeScript 不久,在阅读 TypeScript 内置工具类型的用法和内部实现的文章时,可能会看到 Pick 工具类型,对于该类型的语法你可能会感到陌生。

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};
type User = {
  id: number;
  name: string;
  address: string;
};
type PickedUser = Pick<User, "id" | "name">;

其实学习新事物一种比较好的方式是使用类比。接下来阿宝哥将借助 JavaScript 中的函数来帮助你快速理解 Pick 工具类型背后的语法。

function Pick(obj, keys) {
  const ret = {};
  for (const key of keys) {
    ret[key] = obj[key];
  }
  return ret;
}
const user = {
  id: 666,
  name: "阿宝哥",
  address: "厦门",
};
const PickedUser = MyPick(user, ["id", "name"]);

在以上代码中,function 是关键字用于声明函数,Pick 是函数名称,而小括号内的 obj 和 keys 是参数,大括号中定义的是函数体。

62afea216b07d.jpg

而对于 Pick 工具类型来说,type 关键字用于给类型取个别名,方便重复使用,Pick 就是类型的名称。尖括号内的 T 和 K 属于类型参数,与 JavaScript 函数中参数的区别是类型参数存储的是类型,而 JavaScript 函数参数存储的是值。

62afea25f05d2.jpg

 其中 extends 是泛型约束的语法,用于约束类型的范围。 大括号中是该工具类型的具体实现,它使用了 TypeScript 映射类型的语法。 

其实,你可以把 TypeScript 内置的工具类型理解成特殊的函数,它们被用于处理 TypeScript 中存在的类型。调用工具类型的方式与调用 JavaScript 函数的区别是使用的是尖括号。

最后,为了便于大家理解,阿宝哥以图片的形式来演示一下 Pick 工具类型的执行过程。

62afea2b1a7f5.jpg
62afea2e5d8f6.jpg
62afea31c1cbc.jpg
来源: 全栈修仙之路

链接: https://www.fly63.com/article/detial/11767


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK