【问题标题】:Extending @types - delete field from interface, add type to field in interface扩展@types - 从界面中删除字段,将类型添加到界面中的字段
【发布时间】:2018-06-22 05:17:40
【问题描述】:

我有来自 npm/@types 类型的 javascript 库。

我需要对@types 进行两个修复,这两个修复仅适用于我的应用程序,因此我无法将它们合并到DefinitelyTyped 存储库中。

我需要:

  1. 从界面中删除其中一个字段。示例:

    // before changes:
    interface A {
            a?:string;
            b?:string;
            c?:string;
    }
    
    // after changes:
    interface A {
            a?:string;
            c?:string;
    }
    
  2. 为界面中的一个字段添加更多类型。示例:

    // before changes:
    interface B {
            a?: C;
    }
    
    // after changes:
    interface B {
            a?: C | D;
    }
    

我还想从外部存储库下载主要的@types 定义。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: typescript typescript-typings definitelytyped typescript-types


    【解决方案1】:

    您不能在 TypeScript 中覆盖现有接口属性的类型声明,但您可以通过扩展类型接口来做到这一点,因为您可以覆盖属性类型:

    interface afterA extends A {
      b?: never;
    }
    
    interface afterB extends B {
      a?: C | D;
    }
    

    【讨论】:

    • 您实际上可以在 TypeScript 中修改(或增加)类型声明,它被称为 declaration merging,但如何做到这一点取决于库类型的定义和导出方式,请参阅 ths question 示例
    • @artem 谢谢!这真的很高兴知道。不幸的是,在这种情况下,声明合并似乎不起作用:“接口的非函数成员应该是唯一的。如果它们不是唯一的,它们必须是相同的类型。”
    • 啊,是的,谢谢,我什至没有注意到这个限制,因为我总是用它来添加属性。
    【解决方案2】:

    这可以通过以下方法解决。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2012-01-23
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多