I have a Typescript class which includes a generic which needs to extend another class and implement an interface. Here is an example
interface IHasImage {
Typescript is not so restrictive as Java or C# so you can do things like that:
interface IHasImage {
imageUrl():string;
}
class Model {
}
// use the Model class like an interface
interface IHasImageModel extends IHasImage, Model{
}
class View<T extends IHasImageModel> {
constructor(arg :T){
arg.imageUrl();
}
}
Edit: In TypeScript 1.6 you can use Intersection types:
interface IHasImage {
imageUrl():string;
}
class Model {
}
class View<T extends IHasImage & Model> {
constructor(arg :T){
arg.imageUrl();
}
}
Missing in the example is what T will be:
In the example below i have added an implementation for T, that can be used as the generic constraint.
interface IHasImage {
imageUrl():string;
}
class Model {
}
class ModelWithImage extends Model implements IHasImage {
imageUrl():string
{
return "http://thepetwiki.com/images/thumb/Kitten.jpg/400px-Kitten.jpg";
}
}
class View<T extends ModelWithImage>
{
value:T;
constructor(arg:T)
{
this.value=arg;
}
}
It looks like this is the only way of doing it that I can find. Not perfectly clean but it does the right thing.
interface IHasImage extends Model{
imageUrl():string;
}
class Model {
}
class View<T extends IHasImage> {
}
Here is a screenshot from the playground verifying that it works:
Edit: Added correct workaround.