为什么我不能在 TypeScript 中以这种方式创建只读数组?
Why can't I make an Array readonly this way in TypeScript?
文档显示了 (#ReadOnlyArray) 如何使用接口来完成它,但是当我探索这种语言时,我想知道为什么它不能正常工作?
type TraverseTuple<T extends Array<unknown>> = {
readonly [P in keyof T]: T[P];
}
const test: TraverseTuple<[string, number, string, number]> = ['s', 1, 'o', 2];
test[1] = 0; // not readonly !
有一个内置的只读数组类型,它使数组成为只读的(除非断言回一个普通数组)。
const test: ReadonlyArray<string|number> = ['s', 1, 'o', 2];
test[1] = 0;
但是,对于元组,您需要创建一个显式类型,如下所示:
const test: Readonly<{ 0: string, 1: number, 2: string, 3: number }> = ['s', 1, 'o', 2];
test[1] = 1;
明确不支持此行为。映射元组的能力最近才被引入 typescript 3.1 this PR。来自公关:
A readonly
, -readonly
, or +readonly
annotation in a homomorphic mapped type currently has no effect on array or tuple elements (we might consider mapping from Array
to ReadonlyArray
and vice versa, although that technically isn't structure preserving because it adds or removes methods).
文档显示了 (#ReadOnlyArray) 如何使用接口来完成它,但是当我探索这种语言时,我想知道为什么它不能正常工作?
type TraverseTuple<T extends Array<unknown>> = {
readonly [P in keyof T]: T[P];
}
const test: TraverseTuple<[string, number, string, number]> = ['s', 1, 'o', 2];
test[1] = 0; // not readonly !
有一个内置的只读数组类型,它使数组成为只读的(除非断言回一个普通数组)。
const test: ReadonlyArray<string|number> = ['s', 1, 'o', 2];
test[1] = 0;
但是,对于元组,您需要创建一个显式类型,如下所示:
const test: Readonly<{ 0: string, 1: number, 2: string, 3: number }> = ['s', 1, 'o', 2];
test[1] = 1;
明确不支持此行为。映射元组的能力最近才被引入 typescript 3.1 this PR。来自公关:
A
readonly
,-readonly
, or+readonly
annotation in a homomorphic mapped type currently has no effect on array or tuple elements (we might consider mapping fromArray
toReadonlyArray
and vice versa, although that technically isn't structure preserving because it adds or removes methods).