在Typescript中扩展通用参数 [英] Extending a generic parameter in Typescript
问题描述
我想创建一个实用程序功能,该功能通过向数组中的每个项目添加isChecked
剔除可观察的属性来创建清单.此函数应如下所示:
I want to create a utility function which creates a checklist by adding an isChecked
knockout observable property to each item in an array. This function should look like this:
createCheckList<T>(allEntities: T[], selected: T[]) : CheckListItem<T> {
...
}
我返回了CheckListItem<T>
,因为此接口应扩展T以添加isChecked
属性.但是,打字稿不允许我这样做:
I am returning a CheckListItem<T>
because this interface should extend T to add the isChecked
property. However, typescript will not allow me to do this:
interface CheckListItem<T> extends T {
isChecked: KnockoutObservable<boolean>;
}
给我错误:
一个接口只能扩展另一个类或接口.
An interface may only extend another class or interface.
有什么办法吗?
推荐答案
没有办法在TypeScript中表达它.
There isn't a way to express this in TypeScript.
您显然可以这样做:
interface CheckListItem<T> {
isChecked: KnockoutObservable<boolean>;
item: T;
}
优点是当对象恰好具有自己的isChecked
属性时不会损坏该对象.
This has the advantage of not breaking the object when it happens to have its own isChecked
property.
这篇关于在Typescript中扩展通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!