【问题标题】:Extending the interface of an exported variable in Typescript在 Typescript 中扩展导出变量的接口
【发布时间】:2019-05-03 17:03:27
【问题描述】:

我是 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 modulenamespacedeclare namespacedeclare constdeclare var,有无import c from 'args';。这些都不起作用,或者我做错了。

【问题讨论】:

标签: typescript typescript-declarations


【解决方案1】:

你可以试试这个:

type IyourTypeThatExtendArgs = { myProperty: string } & args;

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

【讨论】:

    猜你喜欢
    • 2016-07-06
    • 2020-11-15
    • 2020-10-30
    • 2020-06-09
    • 2017-10-21
    • 2020-04-09
    • 2018-06-20
    • 2018-04-09
    • 1970-01-01
    相关资源
    最近更新 更多