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?
Generic Classes and SubtypingYou can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.
When generic type invocation happens, the T and E in extends MyGeneric<T, E> would be replaced by type arguments which replaces type parameters T and E in Extend1<T, E> . So, in fact, both generic and non-generic types can extends/implements non-generic types only.
TypeScript fully supports generics as a way to introduce type-safety into components that accept arguments and return values whose type will be indeterminate until they are consumed later in your code.
The extends keyword is used in class declarations or class expressions to create a class that is a child of another class.
Since TypeScript 1.6 you can use intersection types:
type CheckListItem<T> = T & {
isChecked: KnockoutObservable<boolean>;
};
There isn't a way to express this in TypeScript.
You can obviously do this instead:
interface CheckListItem<T> {
isChecked: KnockoutObservable<boolean>;
item: T;
}
This has the advantage of not breaking the object when it happens to have its own isChecked
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With