6

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> {
    ...
}

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>;
}

Gives me the error:

An interface may only extend another class or interface.

Is there any way to do this?

4

2 回答 2

7

从 TypeScript 1.6 开始,您可以使用交集类型

type CheckListItem<T> = T & {
  isChecked: KnockoutObservable<boolean>;
};
于 2017-12-16T21:16:49.630 回答
3

没有办法在 TypeScript 中表达这一点。

您显然可以这样做:

interface CheckListItem<T> {
    isChecked: KnockoutObservable<boolean>;
    item: T;
}

这样做的好处是在对象碰巧有自己的isChecked属性时不会破坏它。

于 2013-09-24T20:47:17.483 回答