首页 > 解决方案 > 在 Typescript 中扩展导出变量的接口

问题描述

我对 TypeScript 很陌生,尤其是在为外部包编写/扩展声明文件方面是新手。

我正在使用argsnpm 包。它是用 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';。这些都不起作用,或者我做错了。

标签: typescripttypescript-declarations

解决方案


你可以试试这个:

type IyourTypeThatExtendArgs = { myProperty: string } & args;

此代码将为您创建新类型,并且 type 将扩展 args 类型。在花括号之间,您可以添加自己的属性,这些属性将与 args 属性一起使用。 &表示右侧旁边的扩展类型。


推荐阅读