I'm aware that in TypeScript, readonly
properties can only be assigned a value within a class constructor. However, I encountered an error while trying to do so inside the constructor of my class, specifically related to an array method handler.
class MyClass {
readonly alpha: number
constructor(settings: Options) {
;(Object.keys(settings) as Array<keyof Options>).forEach((key: keyof Options) => {
// This is not allowed (error: Cannot assign to '...' because it is a read-only property.)
this[key] = settings[key]
// Also not allowed
this.alpha = settings.alpha
})
// This is allowed
this.alpha = settings.alpha
// This is also allowed
const key = 'alpha'
this[key] = settings.alpha
}
}
Can anyone explain why this error occurs and suggest a way to handle it without compromising the use of an array method?