The code below doesn't work and I got stuck. How to I fix this?
type Data = {
id: number,
name: string
}
class Person {
id: number
name: string
constructor(personData: Data) {
this.id = personData.id
this.name = personData.name
}
update(updateData: Data) {
for (const prop in updateData) {
this[prop as keyof Data] = updateData[prop as keyof Data]
}
}
}
Playground link
the Error:
TS2322: Type 'string | number' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'.
The important line is in the update method: this[prop as keyof Data] = updateData[prop as keyof Data]. I suppose that typescript doesn't know that this[prop] and updateData[prop] are the same type (string|number). If all properties are the same type, there is no error. But how to tell typescript, that they are the of the same type?
Seems like it would be better to use composition here. That easily sidesteps the problem you're having.
type Data = {
id: number,
name: string
}
class Person {
data: Data
constructor(personData: Data) {
this.data = personData
}
update(updateData: Data) {
this.data = updateData
}
}
If you really want to be able to access id and name as properties on a Person instance, you could add get accessors for them:
get id() { return this.data.id }
get name() { return this.data.name }
Playground
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