TypeScript return immutable/const/readonly 数组

TypeScript return immutable/const/readonly Array

我想要一个 returns 数组的函数,但我希望返回的数组是只读的,所以当我尝试更改其内容时我应该得到一个 warning/error。

function getList(): readonly number[] {
   return [1,2,3];
}


const list = getList();
list[2] = 5; // This should result in a compile error, the returned list should never be changed

这可以在 TypeScript 中实现吗?

这似乎有效...

function getList(): ReadonlyArray<number> {
    return [1, 2, 3];
}

const list = getList();

list[0] = 3; // Index signature in type 'ReadonlyArray<number>' only permits reading.

Playground

试试

ReadonlyArray<T>是这样实现的:

interface ReadonlyArray<T> {
    readonly [n: number]: T;
    // Rest of the interface removed for brevity.
}

TypeScript 有一个 ReadonlyArray<T> 类型可以做到这一点:

TypeScript comes with a ReadonlyArray type that is the same as Array with all mutating methods removed, so you can make sure you don’t change your arrays after creation

function getList(): ReadonlyArray<number> {
   return [1,2,3];
}

const list = getList();
list[2] = 5; // error

for (const n of list) {
    console.log(n);
}

以下将使列表变为只读,但其中的项目不是:

function getList(): Readonly<number[]> {
   return [1,2,3];
}

let list = getList();
list = 10; // error
list[1] = 5 // that is fine

而这个将使列表及其中的项目变为只读:

function getList(): ReadonlyArray<number> {
   return [1,2,3];
}

let list = getList();
list = 10; // error
list[1] = 5 // error as well

TypeScript 3.4 introduced a new syntax for ReadonlyArray:

以来,来自 OP 的代码现在可以正常工作

While it's good practice to use ReadonlyArray over Array when no mutation is intended, it's often been a pain given that arrays have a nicer syntax. Specifically, number[] is a shorthand version of Array<number>, just as Date[] is a shorthand for Array<Date>.

TypeScript 3.4 introduces a new syntax for ReadonlyArray using a new readonly modifier for array types.

这段代码现在可以正常工作了:

function getList(): readonly number[] {
   return [1,2,3];
}

const list = getList();
list[2] = 5; // <-- error

Playground.