DEV Community

Saulo Dias
Saulo Dias

Posted on

How to extend interfaces in TypeScript

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>[];
}
Enter fullscreen mode Exit fullscreen mode

KeyValue was a generic type imported from @angular/common, but I needed a new property called descriptionin the sourceslist items.

interface KeyValue<K, V> {
  key: K;
  value: V;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Once I did that, all I needed to do was to use it as the new type for sources.

export interface ITemplateField { 
  sources?: Source[];
}
Enter fullscreen mode Exit fullscreen mode

Works like a charm.

Top comments (0)