extending interface with generic in typescript

前端 未结 3 559
余生分开走
余生分开走 2020-12-15 22:56

I want to build an function which takes any object and return that object with few added properties. Something like:

    //this code doesn\'t work   
                


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-15 23:22

    Interface IPropertiesToAdd defines a type variable T that is used to extend an interface named T. This is not possible. An interface can not be referred using a variable name; it must have a fixed name, e.g. Evnt:

    interface Evnt {
      name: T;
    }
    
    interface IPropertiesToAdd extends Evnt {
      on(): void;
      off(): void;
    }
    

    I am not sure what you are trying to achieve in your case. I have extended the example a bit, so it compiles:

    function addProperties(object: Evnt): IPropertiesToAdd {
      /* minimum implementation to comply with interface*/
      var ext:any = {};
      ext.name = object.name
      ext.on = function() {};
      ext.off = function() {};
      return ext;
    };
    
    interface Evnt {
      name: T;
    }
    
    interface IPropertiesToAdd extends Evnt {
      on(): void;
      off(): void;
    }
    
    //usage example
    var str = {name: 'Hello'}
    var evnt = addProperties(str)
    evnt.charAt(3); // error because evnt is not of type 
                    // `string` but `IPropertiesToAdd`
    evnt.on()
    

提交回复
热议问题