Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a generic parameter in Typescript

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?

like image 540
Grokys Avatar asked Sep 24 '13 17:09

Grokys


People also ask

Can you extend a generic class?

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.

Can generic types extend generic types?

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.

Does TypeScript support generic?

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.

What does Extends do TypeScript?

The extends keyword is used in class declarations or class expressions to create a class that is a child of another class.


2 Answers

Since TypeScript 1.6 you can use intersection types:

type CheckListItem<T> = T & {
  isChecked: KnockoutObservable<boolean>;
};
like image 174
ominug Avatar answered Nov 08 '22 17:11

ominug


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.

like image 3
Ryan Cavanaugh Avatar answered Nov 08 '22 16:11

Ryan Cavanaugh