【发布时间】:2020-11-21 14:05:22
【问题描述】:
使用const assertion,可以很好地将对象/数组字面量的类型缩小到其元素。
例如
const arr = [
[5, "hello"],
[5, "bye"],
] as const;
type T = typeof arr; // type T = readonly [readonly [5, "hello"], readonly [5, "bye"]]
(如果没有as const,T 将是type T = (string | number)[][],它非常宽,有时不需要。)
现在,问题是由于as const,数组也变成了readonly,而我只是将它的类型缩小了。所以,它不能传递给下面的函数。
function fiveLover(pairs: [5, string][]): void {
pairs.forEach((p) => console.log(p[1]));
}
fiveLover(arr); // Error
错误是:
'readonly [readonly [5, "hello"], readonly [5, "bye"]]'类型的参数不能分配给'[5, string][]'类型的参数。'readonly [readonly [5, "hello"], readonly [5, "bye"]]'类型为'readonly',不能赋值给可变类型'[5, string][]'.(2345)
问题
如何缩小类型,而不会获得不需要的readonly 属性? (最好在对象/数组创建时。)
【问题讨论】:
标签: typescript constants readonly mutable narrowing