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?
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.