扩展@types - 从接口中删除字段,将类型添加到接口中的字段
Extending @types - delete field from interface, add type to field in interface
我有 javascript 库,其中包含来自 npm/@types 的类型。
我需要对仅适用于我的应用程序的@types 进行两个修复,因此我无法将它们合并到 DefinitelyTyped 存储库中。
我需要:
从界面中删除一个字段。示例:
// before changes:
interface A {
a?:string;
b?:string;
c?:string;
}
// after changes:
interface A {
a?:string;
c?:string;
}
在界面中的一个字段中添加更多类型。示例:
// before changes:
interface B {
a?: C;
}
// after changes:
interface B {
a?: C | D;
}
此外,我还想从外部存储库下载主要的@types 定义。
实现此目标的最佳方法是什么?
您不能覆盖 TypeScript 中现有接口属性的类型声明,但您可以通过扩展类型接口来做到这一点,因为您可以覆盖 属性 类型:
interface afterA extends A {
b?: never;
}
interface afterB extends B {
a?: C | D;
}
可以通过以下方法解决
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;
}
我有 javascript 库,其中包含来自 npm/@types 的类型。
我需要对仅适用于我的应用程序的@types 进行两个修复,因此我无法将它们合并到 DefinitelyTyped 存储库中。
我需要:
从界面中删除一个字段。示例:
// before changes: interface A { a?:string; b?:string; c?:string; } // after changes: interface A { a?:string; c?:string; }
在界面中的一个字段中添加更多类型。示例:
// before changes: interface B { a?: C; } // after changes: interface B { a?: C | D; }
此外,我还想从外部存储库下载主要的@types 定义。
实现此目标的最佳方法是什么?
您不能覆盖 TypeScript 中现有接口属性的类型声明,但您可以通过扩展类型接口来做到这一点,因为您可以覆盖 属性 类型:
interface afterA extends A {
b?: never;
}
interface afterB extends B {
a?: C | D;
}
可以通过以下方法解决
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;
}