Home > Enterprise >  Extending recursive Typescript interfaces
Extending recursive Typescript interfaces

Time:10-15

I'm using the TS type for JSON Schema: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/json-schema/index.d.ts

Short version:

interface JSONSchema4 {
  properties?: {
    [k: string]: JSONSchema4;
  } | undefined;
}

This type is recursive. I'd like to extend this type with custom properties. E.g. currently, something like this doesn't match the type:

{ instanceof: 'Date' }

I'd like to add instanceof?: string as a field to JSONSchema4. Is this possible?

CodePudding user response:

In TypeScript, interfaces are open, unlike types that are closed. So, you can add your keyword simply by declaring an interface with the same name that contains your keyword. That interface effectively extends the original type.

interface JSONSchema4 {
  instanceof?: string;
}
  • Related