【问题标题】:extending interface with generic in typescript在打字稿中使用泛型扩展接口
【发布时间】:2014-10-30 11:48:12
【问题描述】:

我想构建一个函数,它接受任何对象并返回该对象并添加少量属性。比如:

    //this code doesn't work   
        function addProperties<T>(object: T): IPropertiesToAdd<T> {/*implmentions code*/};

        interface IPropertiesToAdd<T> extend T{
            on(): void;
            off(): void;
        }

//usage example
var str = new String('Hello')
addProperties(str)
str.charAt(3)
str.on() 

对于上面的代码typescript编译器返回一个接口只能添加一个类或者接口的错误,我该如何在typescript中表达呢。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以创建一个新的type alias,这将允许您的对象继承另一种对象类型的功能。我找到了这段代码here。

    type IPropertiesToAdd<T extends {}> = T & {    // '{}' can be replaced with 'any'
        on(): void
        off(): void
    };
    
    interface ISomething {
        someValue: number
    }
    
    var extendedType: IPropertiesToAdd<ISomething> = {
        on(): void {
            console.log("switched on");
        },
        off(): void {
            console.log("switched off");
        },
        someValue: 1234,
    };
    

    我对此进行了测试,似乎'T'可以是接口、类和数组类型。我无法让联合类型工作。

    这仅适用于匿名对象,不能用于实际继承目的。

    希望这会有所帮助。

    【讨论】:

    • 链接已损坏
    【解决方案2】:

    接口IPropertiesToAdd 定义了一个类型变量T,用于扩展名为T 的接口。这是不可能的。不能使用变量名引用接口;它必须有一个固定的名称,例如事件:

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

    我不确定您要在您的情况下实现什么。我对示例进行了一些扩展,因此可以编译:

    function addProperties<T>(object: Evnt<T>): IPropertiesToAdd<T> {
      /* minimum implementation to comply with interface*/
      var ext:any = {};
      ext.name = object.name
      ext.on = function() {};
      ext.off = function() {};
      return ext;
    };
    
    interface Evnt<T> {
      name: T;
    }
    
    interface IPropertiesToAdd<T> extends Evnt<T> {
      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<string>`
    evnt.on()
    

    【讨论】:

    • 感谢您抽出宝贵时间,对架构稍作改动,您的回答确实很有帮助。
    【解决方案3】:

    我解决了这个问题:

    type IModelProperty<T = Record<string, any>> = T & {
         on(): void;
         off(): void;
    };
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2019-01-20
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      相关资源
      最近更新 更多