在打字稿中使用泛型扩展接口 [英] extending interface with generic in typescript
问题描述
我想构建一个函数,它接受任何对象并返回该对象并添加很少的属性.类似的东西:
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
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()
对于上面的代码打字稿编译器返回一个接口只能添加一个类或接口的错误,我如何在打字稿中表达这一点.
For the above code typescript compiler return the error that an interface can only add a class or interface, how I can express this in typescript.
推荐答案
您可以创建一个新的 type alias 这将允许您的对象继承另一种对象类型的功能.我在此处找到了这段代码.>
You can create a new type alias which will allow your object to inherit the features of another object type. I found this bit of code 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"可以是接口、类和数组类型.我无法让联合类型发挥作用.
I've tested this, and it seems that 'T' can be an interface, class, and an array type. I couldn't get union types to work.
这只适用于匿名对象,不能用于实际的继承目的.
This only works on anonymous objects, it can't be used for actual inheritance purposes.
希望这会有所帮助.
这篇关于在打字稿中使用泛型扩展接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!