Describe the shape of an object

INPUT · Slides

Arrays you cannot change

01 / 05

Arrays can be readonly too

Remember putting readonly on an object property to declare "this does not change later"? You can do the same to an array itself.

You write it by putting readonly in front of the array type. readonly string[] means "a read-only array of strings".

const colours: readonly string[] = [  "red",  "blue",];console.log(colours.length);

Result

2

02 / 05

push is simply not there

An array marked readonly does not come with the methods that change its contents. Try to call push and you are told there is no such property.

Not "you can call it but you will be told off" — it was never there. That is quite a strong declaration.

const colours: readonly string[] = [  "red",];colours.push("blue");

Result

Type error: Property 'push' does not exist on type 'readonly string[]'.

03 / 05

Swapping by position is stopped too

Swapping one out by position, as in colours[0] = "yellow", does not go through either.

Remember that all const protects is which array the variable points at; changing the contents went through. readonly guards the contents for you.

const colours: readonly string[] = [  "red",];colours[0] = "yellow";

Result

Type error: Index signature in type 'readonly string[]' only permits reading.

04 / 05

Reading works as it always did

The only thing forbidden is changing. Looking at length, taking one out by position, going round with for...of — all exactly as with an ordinary array.

Declaring in the type that an array is read-only stops an accidental change on the spot. Whoever touches it later need not know the rule.

const colours: readonly string[] = [  "red",  "blue",];for (const c of colours) {  console.log(c);}

Result

red
blue

05 / 05

When you want a different one, make a new one

Want to add something? Spread it with ... and make a new array. The original stays as it was.

push changes the original; this prepares something else. Make a function parameter readonly and you have promised "this function does not change the array you gave it". Very reassuring for whoever reads it. Let us write some.

const colours: readonly string[] = [  "red",];const more: readonly string[] = [  ...colours,  "green",];console.log(more);console.log(colours);

Result

["red", "green"]
["red"]