The type 'readonly ....' is 'readonly' and cannot be assigned to the mutable type Ошибка
Primary tabs
Проблема
The type 'readonly {....}[]' is 'readonly' and cannot be assigned to the mutable type
Возникает для кода вида:
let deliveryTypes = [ { value: 1, label: 'Без доставки'}, { value: 2, label: 'Страна'}, { value: 3, label: 'Город'}, ]; deliveryTypes = Object.freeze(deliveryTypes); export { deliveryTypes };
Причина
Полное сообщение об ошибке в моем случае выглядит так:
The type 'readonly { value: number; label: string; }[]' is 'readonly' and cannot be assigned to the mutable type '{ value: number; label: string; }[]'. TS4104 3 | { value: 3, label: 'Город'},]; 4 | > 5 | deliveryTypes = Object.freeze(deliveryTypes); | ^ 6 | 7 | export { deliveryTypes };
И связано оно с тем, что let deliveryTypes изначально имеет по-умолчанию изменяемый тип, а мы ему присваиваем неизменяемвый тип, который возращается из Object.freeze()
Решение
Самая быстрая правка, это заморозка массива в момент объявления:
let deliveryTypes = Object.freeze( [{ value: 1, label: 'Без доставки' }, { value: 2, label: 'Страна' }, { value: 3, label: 'Город' },] ); export { deliveryTypes };
- Log in to post comments
- 2192 reads