I am facing an issue with two TypeScript classes where one extends the other:
type NamedObject = {
name: string;
}
class AnyObjectManager {
objectList = [];
getAnyObject = (matches: (o: object) => boolean) => {
for (const o of this.objectList) {
if (matches(o)) {
return o;
}
}
return null;
}
}
class NamedObjectManager extends AnyObjectManager {
getObjectNamedTim = () => {
return this.getAnyObject(this.objectIsNamedTim)
}
objectIsNamedTim = (namedObject: NamedObject) => {
return namedObject.name === 'Tim';
}
}
An error is being displayed by TypeScript in the method NamedObjectManager.getObjectNamedTim:
TS2345: Argument of type '(namedObject: NamedObject) => boolean' is not assignable to parameter of type '(o: object) => boolean'.
Types of parameters 'namedObject' and 'o' are incompatible.
Property 'name' is missing in type '{}' but required in type 'NamedObject'.
I want to ensure that all objects managed by NamedObjectManager will be NamedObjects, as functions like addObject guarantee this. How can I communicate to TypeScript that we can safely assume this in methods inherited from the parent class?