Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
haz111 Avatar asked Jan 12 '18 17:01

haz111


People also ask

How do I modify a TypeScript interface?

Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.

What is the difference between interface and type in TypeScript?

// One major difference between type aliases vs interfaces are that interfaces are open and type aliases are closed. This means you can extend an interface by declaring it a second time. // In the other case a type cannot be changed outside of its declaration.

How do I omit with interface TypeScript?

Use the Omit utility type to extend an interface excluding a property, e.g. type WithoutTasks = Omit<Employee, 'tasks'>; . The Omit utility type constructs a new type by picking the properties from the provided type and removing the specified keys.

What is ?: In TypeScript?

Using ?: with undefined as type definition While there are no errors with this interface definition, it is inferred the property value could undefined without explicitly defining the property type as undefined . In case the middleName property doesn't get a value, by default, its value will be undefined .


2 Answers

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;
}
like image 110
Abhishek Prakash Avatar answered Sep 20 '22 21:09

Abhishek Prakash


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;
}
like image 24
Explosion Pills Avatar answered Sep 23 '22 21:09

Explosion Pills