Extending @types - delete field from interface, add type to field in interface

haz111 picture haz111 · Jan 12, 2018 · Viewed 7.1k times · Source

I have javascript library with types from npm/@types.

I need to make two fixes to @types which applies only in case of my application, so I can't merge them into DefinitelyTyped repository.

I need to:

  1. remove one of fields from interface. Example:

    // before changes:
    interface A {
            a?:string;
            b?:string;
            c?:string;
    }
    
    // after changes:
    interface A {
            a?:string;
            c?:string;
    }
    
  2. add more types to one field in interface. Example:

    // before changes:
    interface B {
            a?: C;
    }
    
    // after changes:
    interface B {
            a?: C | D;
    }
    

Also I still want to download main @types definitions from external repository.

What is the best way to achieve this?

Answer

Explosion Pills picture Explosion Pills · Jan 12, 2018

You cannot override type declarations of existing properties of interfaces in TypeScript but you could do this by extending the type interfaces since you can override property types:

interface afterA extends A {
  b?: never;
}

interface afterB extends B {
  a?: C | D;
}