我在TypeScript中有这个代码片段:
const arr: ReadonlyArray<string> = [ "123", "234" ]; arr.push("345");TS编译器显示错误: Property 'push' does not exist on type 'ReadonlyArray<string>' 。 当然很明显我不能改变/改变这个数组,但问题是 - ReadonlyArray的基类是什么? 它是否继承自标准的Array类?
I have this code snippet in TypeScript:
const arr: ReadonlyArray<string> = [ "123", "234" ]; arr.push("345");TS compiler shows an error:
Property 'push' does not exist on type 'ReadonlyArray<string>'.
Of course, it's clear that I cannot change/alter this array. The question is: what is the base class for ReadonlyArray? Does it inherit from standard Array class?
最满意答案
https://www.typescriptlang.org/docs/handbook/interfaces.html表明
TypeScript附带一个ReadonlyArray<T>类型,与Array<T>相同,删除了所有变异方法,因此您可以确保在创建后不更改数组
如果你想要源,请转到
https://github.com/Microsoft/TypeScript/blob/master/src/lib/es5.d.ts#L978
(其定义在当前版本的第978行)。
https://www.typescriptlang.org/docs/handbook/interfaces.html states that:
TypeScript comes with a ReadonlyArray<T> type that is the same as Array<T> with all mutating methods removed, so you can make sure you don’t change your arrays after creation
If you want the source, head over to:
https://github.com/Microsoft/TypeScript/blob/master/src/lib/es5.d.ts#L978
(its definition is on the line 978 in the current version).
更多推荐
发布评论