I'm trying to migrate from TypeScript 2.3.2 to 2.4.2.
This code used to work in 2.3:
class Records {
public save(): Records {
return this;
}
}
class User extends Records {
public update(): User {
return this.save();
}
}
let myUser: User = new User();
let obj = myUser.update();
but now, it raises the following error on compilation:
Error:(10, 5) TS2322: Type 'Records' is not assignable to type 'User'. Property 'update' is missing in type 'Records'.
Of course, I can change update so that it returns "Records" like this:
public update(): Records {
return this.save();
}
But I don't really get why I have to change this. It looks like a regression to me. Anyone have an explanation or a better solution ? I find it makes my code harder to read.
Thanks a lot,
Julien
It's a typing issue. You are saying that
User.updatewill return aUser, but it actually returns the result ofRecords.save, which is of typeRecords. TheRecordstype cannot be assigned to something expecting aUserbecauseRecordsdoes not have theupdatemethod.In order to fix this, you must specify the return type of
updateto beRecords(which it is currently returning) or you will need to modifyRecords.saveto return aUser(which will require changing the implementation of the method) -- your solution will depend on what you need from your program.I think part of your confusion may come from the
extendskeyword -- it may seem likeUserandRecordsare kind of the same sinceUser"extends"Records, but this is not the case. Read more aboutextendsin the "Inheritance" section of this article: https://www.typescriptlang.org/docs/handbook/classes.htmlIn response to your comments (assuming you cannot change the implementation), a more accurate type for your
savemethod would be a Union type ofUser | Recordssince it will return one or the other depending on the context in which it is called.That would look like this:
Read about Union types here: https://www.typescriptlang.org/docs/handbook/advanced-types.html