The other day I had the following problem: the property sources
in my interface ITemplateField
was a list of key-value objects.
export interface ITemplateField {
sources?: KeyValue<string, string>[];
}
KeyValue
was a generic type imported from @angular/common
, but I needed a new property called description
in the sources
list items.
interface KeyValue<K, V> {
key: K;
value: V;
}
I couldn't (and I shouldn't) create a new parameter in the KeyValue
generic type. First, it is a library import, which I couldn't change unless I changed the implementation in the library, and second, it is a key-value generic interface, and we should never pollute generic scopes.
Enter interface extensions
I decide creating a new interface named Source
, which extends KeyValue<string, string>
interface Source extends KeyValue<string, string> {
description: string;
}
Once I did that, all I needed to do was to use it as the new type for sources
.
export interface ITemplateField {
sources?: Source[];
}
Works like a charm.
Top comments (0)