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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more