惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
博客园_首页
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
MongoDB | Blog
MongoDB | Blog
美团技术团队
H
Help Net Security
G
Google Developers Blog
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
M
MIT News - Artificial intelligence
腾讯CDC
IT之家
IT之家
Vercel News
Vercel News
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
I
InfoQ
博客园 - 司徒正美
A
About on SuperTechFans

Ray's Blog

从 GitHub Discussions 自动生成静态评论区 — Ray's Blog 给 2025 年的告别 — Ray's Blog Ray's Blog 可重用的工作流 — Ray's Blog Ray's Blog 把博客用 Nuxt Content 重写及踩坑记录 — Ray's Blog Ray's Blog 你这个级别的 Devtools 无权哈我 — Ray's Blog 辞旧迎新:Ray 的 2024 年终总结 — Ray's Blog Ray's Blog 使用 ip6tables 在群晖 DiskStation 上开启 Docker Bridge 网络 IPV6 支持(不支持 SA6400) — Ray's Blog Ray's Blog 迟来了一个月的 2023 年度总结 + 2024 新年快乐! — Ray's Blog Vue Language Tools 深度解析 (1):Vue 编辑器插件发展历程及基本工作原理 — Ray's Blog Ray's Blog Ray's Blog Ray's Blog 快使用 Dprint 换掉你的 Prettier 罢(迫切 — Ray's Blog Ray's Blog chi 的小红包冒险 v.e.r. 2023 — Ray's Blog Ray's Blog 打造一个强大的 PowerShell 终端 =) — Ray's Blog Ray's Blog 2023 新年快乐! + 年度总结 — Ray's Blog Ray's Blog Clerc:一个轻量但强大的命令行框架 — Ray's Blog Ray's Blog 无服务器动态博客系统 Dolan:从设想到现实 — Ray's Blog Ray's Blog 使用 Scoop + 版本管理器科学地管理你的开发环境! — Ray's Blog
TypeScript 小寄巧!如何在不使用 const 泛型修饰符的情况下...
2023-05-13 · via Ray's Blog

正文

在开始之前我们先来看几个代码片段:

const a = <T extends string>(t: T) => t;const b = <T extends number>(t: T) => t;const c = <T extends boolean>(t: T) => t;

此时我们这样调用它们,请问返回值的类型是什么?

const d = a("a");const e = b(1);const f = c(true);

好了不卖关子了,上面三个变量的类型分别是"a"1true。很符合直觉对吧?他们的参数都是字面量类型,因此泛型 T 也是对应的字面量,返回值 T 便是传入参数本身。

我们现在得到了这些能够从参数推导出字面量的函数,让我们把它推广到列表试试(Playground 链接):

const g = <T extends string[]>(t: T) => t;const h = g(["111", "222"]); // 寄,类型是string[]

奇怪,为什么类型是 string[] 而不是更为具体的 ["111", "222"] 呢?或许是因为这个列表能够被函数体所修改罢,谁知道呢。

如果我们确实想让返回值的类型和传入参数的类型所匹配,但不想加上 as const 修饰符(因为它会让类型变为 readonly ["111","222"]),那我们怎么做呢?最近 TypeScript 5.0 的更新中加入了 const 泛型修饰符,能够在不用 as const 断言的情况下推导出字面量类型,然而它的结果也是 readonly ,这不是我们所想要的

其实你只需要做一些小小的改动(Playground 链接):

const g = <T extends string[]>(t: [...T]) => t; // 这里t的类型用了一个展开运算const h = g(["111", "222"]); // 好,类型变成["111", "222"]了

就可以得到我们想要的结果。

不清楚为什么能这么用,不过用就完事了