Typescript generics extending class and interface

后端 未结 3 677
我寻月下人不归
我寻月下人不归 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<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();
        }
    }
    
    0 讨论(0)
  • 2020-12-15 07:06

    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;
        }       
    }
    
    0 讨论(0)
  • 2020-12-15 07:15

    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:

    playground

    Edit: Added correct workaround.

    0 讨论(0)
提交回复
热议问题