typescript - 在 Typescript 中扩展导出变量的接口
问题描述
我对 TypeScript 很陌生,尤其是在为外部包编写/扩展声明文件方面是新手。
我正在使用args
npm 包。它是用 JavaScript 编写的,所以它的类型在@types/args
.
/**
* args/lib/index.js
*/
const publicMethods = {
option: require('./option'),
options: require('./options'),
command: require('./command'),
parse: require('./parse'),
example: require('./example'),
examples: require('./examples'),
showHelp: require('./help'),
showVersion: require('./version')
}
function Args() {
this.details = {
options: [],
commands: [],
examples: []
}
/* ... */
}
/* ...assign `publicMethods` to `Args` class... */
module.exports = new Args()
/**
* @types/args/index.d.ts
*/
declare const c: args;
export = c;
interface args {
/* ... */
}
/* ... */
该类args
有一个名为details
(虽然我不知道为什么它是私有的)的私有属性,它不是由@types/args
. 我想扩展 args 接口以公开属性,以便我可以遍历选项,但由于导出是变量而不是模块,我还没有弄清楚如何。
我试过使用declare module
, namespace
, declare namespace
, declare const
, and declare var
, 有和没有import c from 'args';
。这些都不起作用,或者我做错了。
解决方案
你可以试试这个:
type IyourTypeThatExtendArgs = { myProperty: string } & args;
此代码将为您创建新类型,并且 type 将扩展 args 类型。在花括号之间,您可以添加自己的属性,这些属性将与 args 属性一起使用。 &表示右侧旁边的扩展类型。
推荐阅读
- ios - 从谷歌地图API绘制方向
- c# - ASP.NET Core MVC - 在 RenderBody() 中渲染视图
- prolog - Prolog - 给定关系的路径查找和长度
- scala - 为什么Scala返回一个';' 预期但“,”发现错误?
- r - 使用 tidyverse 在数据框中查找多个变量的第一个非零年份
- ios - iOS/UIKit 是否内置了对像 dinging 这样的调度滚动的支持
- python - 在Python中根据另一个数组中的索引创建一个数组
- javascript - Jquery Selector 获取以前的 aria-selector 元素,而不是当前元素
- math - 如何用旋转和平移矩阵求解方程?
- mongoose - Mongoose Document.toObject 产生 GraphQL 错误