2014-10-30 232 views
1

通用扩展接口我想建立一个功能女巫采取任何对象,并返回该对象很少添加的属性。是这样的:在打字稿

//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() 

上面的代码编译打字稿返回错误的接口只能添加一个类或接口,我怎么能在打字稿表达这一点。

回答

8

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

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() 
+0

感谢您的时间,在架构变化不大,你的答案真的帮助。 – user2692945 2014-10-30 14:26:30

3

您可以创建一个新的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'可以是接口,类和数组类型。我无法使用工会类型。

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

希望这会有所帮助。