【发布时间】:2022-10-07 02:23:45
【问题描述】:
TypeScript 支持条件类型,使用 \'extends\' 关键字和三元运算符。
eval 为 true 的示例条件类型:
type C1 = 7 extends number ? true : false
type C2 = 7 extends number | string ? true : false
type C3 = 7 extends 7 | \'cat\' | null ? true : false
type C4 = [1,2,3] extends [1,2,3] ? true : false
type C5 = any[] extends any[] ? true : false
我理解上述条件(即使 \'extends\' 在非 OOP 上下文中看起来很奇怪)。
以下条件我不明白:
type Q1 = any[] extends readonly any[] ? true : false // evals to true
type Q2 = readonly any[] extends any[] ? true : false // evals to false
为什么 Q1 评估为真,而 Q2 评估为假?我的预期正好相反,因为只读数组似乎比一般数组“更具体”。
在这种情况下,“扩展”的真正含义是什么?
我正在使用TypeScript Playground 来测试这些条件。
-
是的,
readonly是一种具有误导性的术语。说onlyKnownToBeReadableAndMayOrMayNotBeWritable会更准确,但没有人愿意处理这个问题。
标签: typescript