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:
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;
}
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?
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.
// 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.
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.
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 .
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With