7

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?

2 Answers 2

21

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

12

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

3 Comments

You actually can modify (or augment) type declaration in TypeScript, it's called declaration merging, but how to do that depends on how exactly library types are defined and exported, see ths question for one example
@artem thanks! This is really good to know. Unfortunately it doesn't look like declaration merging will work in this case: "Non-function members of the interfaces should be unique. If they are not unique, they must be of the same type."
Ah yes thanks, I did not even notice that restriction, because I always use it only to add properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.