首页 > 解决方案 > 打字稿:使用模块扩充在内部对象上添加属性

问题描述

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

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

如何使用模块扩充somesubvar2在内部添加属性?suboptions

我在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; }'.

标签: typescriptmodule-augmentation

解决方案


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

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对象是直接成员并且它是undefined原始Contract 类型。

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

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


推荐阅读