interface Parent {
name: string;
}
interface Child extends Parent {
name: string;
text: string;
}
function myFunction(text: string, target: Child): Child {
target.text = text;
console.log(target);
return target;
}
const testChild: Child = {
name: 'test',
text: 'sample',
};
declare type FunctionType = (text: string, target: Parent) => Parent;
const func: FunctionType = myFunction;
func('newText', testChild);
This snippet results in an error because the FunctionType expects a function with Parent as parameters and return value, rather than Child. Is there a way to modify it so that it can work with direct subclasses of Parent like Child?
When could this be beneficial? Consider a scenario where we have an Angular component that accepts basic slim items represented by the Parent interface and a handler function. However, we wish to pass a Child item along with its corresponding handler function (myFunction in this case) to the component. The internal functions of the component only interact with fields related to the Parent. Although subclassing the parent component's class in Angular and overriding properties is a potential solution, creating a new component or class for each new Child type could become cumbersome. This is just an example scenario.
In essence, how can we define a function type that accommodates not only the Parent interface but also all child interfaces without explicitly listing them?
The ultimate goal is to adhere to the substitution principle: what works for the parent should seamlessly apply to its children as well.