TypeScript 类型转换应该尝试移除只读修饰符,

vqlkdk9b  于 3个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(44)

编译器在无法将只读元组转换为可变数组时,应尽量使用可变版本的只读元组,主要是为了 as const 的可用性。这种性能影响较小,因为运行此检查的条件有限。

TypeScript 版本: 3.7.x-dev.20200123
搜索词:
代码:

([0] as [0]) as number[];
([0] as [0]) as readonly number[];
// As the expansion of [0] as const
([0] as readonly [0]) as number[]; // error
([0] as readonly [0]) as readonly number[];

预期行为:

通过

实际行为:

Conversion of type 'readonly [0]' to type 'number[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  The type 'readonly [0]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.(2352)

** playground 链接:**http://www.typescriptlang.org/play/index.html?target=99&ts=3.8.0-dev.20200123&ssl=1&ssc=1&pln=6&pc=1#code/BQbQDAugBAhgzlcECUsEDsCuBbARgUwCcQIBuAKFEjUUlXikPxgBMB7dAGwE8os8iJCgHphUAIIIALgAt8UfAA8ADjHRwAlhyhsAZrWgMAxhzhTKSGk1YceB+hhwFiZKKIWFCbQheoNr7Fy8SA6MzIF2-M5C5EA
相关问题:

8i9zcol2

8i9zcol21#

直觉上,这些类型似乎有足够的重叠,因此这应该是一个允许的转换,尤其是考虑到允许的内容:

declare var c: readonly [number];
c as number[]; // fails
c as [number] as number[]; // succeeds

相关问题