Generic type constraint in variable/field declaration

282 views Asked by At

Suppose we have a generic interface:

export interface IKeyValue<K, V> {
    key: K;
    value: V;
}

Now, we want to declare a variable/field and limit which types could be used as K and V:

public items: IKeyValue<K extends Type1, V extends Type2>[];

The code above doesn't compile.

I'm using TypeScript 2.6.

How can we achieve it in TypeScript?

1

There are 1 answers

1
Igor On BEST ANSWER

That is because you are not providing a definition but an instance.

public items: IKeyValue<Type1, Type2>[];

...is the valid syntax.


If you want to restrict the definition (interface) then you can provide the extends:

export interface IKeyValue<K extends Type1, V extends Type2> {
    key: K;
    value: V;
}