typescript - 打字稿:使用模块扩充在内部对象上添加属性
问题描述
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; }'.
解决方案
这本可以做得更好,使用环境声明在全球范围内可用,但它仍然可以完成工作。
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
类型。
Modify
:https
ModifyDeep
: //stackoverflow.com/a/55032655/985454:https: //stackoverflow.com/a/65561287/985454
推荐阅读
- neural-network - DarkNet - 没有检测到自定义训练数据
- swift - Firebase Default Parameters not logging to Events Dashboard
- c# - 如何将这两种方法结合起来?
- java - 获取数组中最便宜的项目组合以达到给定值
- css - 从显示中排除元素
- amazon-web-services - Logstash S3 输出插件中的自定义域
- python - 在 Tensorflow 中使用 py_func - ValueError:找不到回调 pyfunc_0
- java - 如何在运行时用不同数量的 editText 对象填充数组列表?
- python - 从列表或元组创建一个新的 numpy 数组
- git - 从主分支中删除许多提交之一,保留其余提交