gpt4 book ai didi

javascript - TypeScript 返回不可变/常量/只读数组

转载 作者:数据小太阳 更新时间:2023-10-29 03:49:02 27 4
gpt4 key购买 nike

我想要一个返回数组的函数,但我希望返回的数组是只读的,所以当我尝试更改其内容时应该会收到警告/错误。

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.
}

关于javascript - TypeScript 返回不可变/常量/只读数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com