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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
NISL@THU
NISL@THU
Know Your Adversary
Know Your Adversary
The Hacker News
The Hacker News
D
Docker
Scott Helme
Scott Helme
有赞技术团队
有赞技术团队
罗磊的独立博客
A
Arctic Wolf
P
Privacy International News Feed
Google DeepMind News
Google DeepMind News
Spread Privacy
Spread Privacy
B
Blog
A
About on SuperTechFans
L
LINUX DO - 最新话题
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
T
The Exploit Database - CXSecurity.com
美团技术团队
J
Java Code Geeks
Cloudbric
Cloudbric
雷峰网
雷峰网
Vercel News
Vercel News
P
Proofpoint News Feed
Webroot Blog
Webroot Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
人人都是产品经理
人人都是产品经理
Martin Fowler
Martin Fowler
G
Google Developers Blog
T
Tenable Blog
PCI Perspectives
PCI Perspectives
Engineering at Meta
Engineering at Meta
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
C
Cybersecurity and Infrastructure Security Agency CISA
S
Secure Thoughts
N
News and Events Feed by Topic
GbyAI
GbyAI
S
SegmentFault 最新的问题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

Ray's Blog

Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog Ray's Blog
Ray's Blog
i@mk1.io (Ra · 2023-05-13 · via Ray's Blog

TypeScript 小寄巧!如何在不使用 const 泛型修饰符的情况下推导出列表字面量?

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

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"]了

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

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