shokha
shokha

Reputation: 3179

What class does ReadonlyArray inherit?

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?

Upvotes: 3

Views: 635

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51683

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#L1121 (01.06.2022) - Search for "ReadonlyArray" if source file evolved.

(its definition is on the line 1121 in the current version).

Upvotes: 5

Related Questions