简体   繁体   中英

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

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?

This can be solved using the following method.

import { A as AContract, B as BContract, C, D } from './contracts.ts';

// Removes 'b' property from A interface.
interface A extends Omit<AContract, 'b'> { }

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM