我想要一个返回数组的函数,但是我希望返回的数组为只读,因此当我尝试更改其内容时应该收到警告/错误。
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.
}