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) };.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With