In my current project, I have a class named Foo that is responsible for holding a list of items. These items all inherit from a base type called IBar. The list can potentially have any number of items.
One challenge I am facing is creating a get method in the Foo class that specifically takes a generic type restricted to only those types that inherit from IBar.
As of now, the interfaces and classes I have defined are as follows:
interface IBar {
bar: string;
}
interface IFizz extends IBar {
buzz: string;
}
class Foo {
get<T extends IBar>(): T {
var item = this.list[0];
return item;
}
list: Array<IBar>;
}
The code I am attempting to run is:
var foo = new Foo();
var item = foo.get<IFizz>();
Although I am aware that the list is currently empty, my main goal is to prevent the TypeScript compiler from displaying an error. The call to `foo.get` does not cause an error, the issue lies within the implementation of the get method itself.
The error message I receive is "Type 'IBar' is not assignable to type 'T'."
When comparing this situation to C#, I believe a similar approach would work. I would greatly appreciate any examples or guidance that could help me resolve this issue.
Thank you.