Typescript generics extending class and interface

后端 未结 3 681
我寻月下人不归
我寻月下人不归 2020-12-15 06:44

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 {
          


        
3条回答
  •  暖寄归人
    2020-12-15 07:05

    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 {
        constructor(arg :T){
           arg.imageUrl();
        }
    }
    

    Edit: In TypeScript 1.6 you can use Intersection types:

    interface IHasImage {
        imageUrl():string; 
    }
    
    class Model {
    }
    
    class View {
        constructor(arg :T){
           arg.imageUrl();
        }
    }
    

提交回复
热议问题