Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript readonly Array property assignment error

I have a question about TypeScript type inference. Here is a simple example.

interface Student {
  readonly ids: number[],
}
const ids: readonly number[] = [1, 2, 3];
let student: Student = { ids: ids };

This code snippet is complaining with the following error message:

The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.

It seems that the type inference requires that the type of ids value inside { ids: ids } must have a type of number[] rather than readonly number[].

I can either remove the readonly in const ids: readonly number[] = [1, 2, 3]; or change let student: Student = { ids: ids }; to let student: Student = { ids: ids.map(id => id) };.

like image 936
Jerry Yuan Avatar asked Aug 20 '26 06:08

Jerry Yuan


1 Answers

You are making the property readonly, not the type of the property. What you should actually do is the following:

interface Student {
  ids: readonly number[];
}

Testing:

const ids: readonly number[] = [1, 2, 3];
let student: Student = { ids: ids }; // no error

The difference is that you are preventing mutating the field itself:

let student: Student = { ids: [] };

student.ids = [1]; // Cannot assign to 'ids' because it is a read-only property
like image 161
wonderflame Avatar answered Aug 23 '26 14:08

wonderflame



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!