【问题标题】:Typescript: Add a property on an inner object with module augmentation打字稿:使用模块扩充在内部对象上添加属性
【发布时间】:2020-08-26 04:31:39
【问题描述】:

考虑一个外部 (npm) 模块 extmod 在其声明文件中公开以下接口:

interface Options {
  somevar?: string;
  suboptions?: {
    somesubvar?: string;
  };
}

如何通过模块扩充在suboptions 中添加属性somesubvar2

我在 extmod.d.ts 文件中尝试了以下内容:

declare module 'extmod' {
  interface Options {
    suboptions?: {
      somesubvar2?: string;
    };
  }
}

但它会引发以下错误:

error TS2687: All declarations of 'suboptions' must have identical modifiers.
error TS2717: Subsequent property declarations must have the same type.  Property 'suboptions' must be of type '<SNIP>', but here has type '{ somesubvar2: string; }'.

【问题讨论】:

标签: typescript module-augmentation


【解决方案1】:

这本可以做得更好,使用环境声明在全球范围内可用,但它仍然可以完成工作。

import Web3 from 'web3'
import type { Contract as TheBadContract } from 'xyz'

interface ContractMethods {
  // some properties...
}

interface Contract extends Modify<TheBadContract, {
  methods: ContractMethods // <- this `methods` is the actual overwritten property
}> {}

const contract: Contract = new web3.eth.Contract()

这很简单,因为 methods 对象是直接成员,它是原始 Contract 类型上的 undefined

如果您需要实际修改一些深度嵌套的键,请查看下面我的ModifyDeep 类型。

Modify:https://stackoverflow.com/a/55032655/985454
ModifyDeep:https://stackoverflow.com/a/65561287/985454

【讨论】:

    【解决方案2】:

    如何在带有模块的子选项中添加属性 somesubvar2 增强?

    在您的示例中,您将类型 suboptions&lt;SNIP&gt; 更改为 { somesubvar2: string; }

    您可以使用附加属性修补 &lt;SNIP&gt; 类型。

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2020-01-10
      • 1970-01-01
      • 2019-06-13
      • 2022-01-11
      • 2014-05-22
      • 2017-09-06
      • 2016-04-26
      • 1970-01-01
      相关资源
      最近更新 更多