打字稿-无法扩充模块

Fen1kz

我正在开发使用打字稿v3.6.4和Twitter API(个人项目)。

我还@types/twithttps://www.npmjs.com/package/@types/twit安装

我想向“列表/成员”端点发出请求

我的代码是:

import Twit from "twit";

const client = new Twit(...);

client.get('lists/members', {list_id: '123123'})

但是,打字稿给我一个错误:

src/data/TwitterProvider.ts:16:34 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(path: string, callback: Callback): void', gave the following error.
    Argument of type '{ list_id: string; }' is not assignable to parameter of type 'Callback'.
      Object literal may only specify known properties, and 'list_id' does not exist in type 'Callback'.
  Overload 2 of 3, '(path: string, params?: Params): Promise<PromiseResponse>', gave the following error.
    Argument of type '{ list_id: string; }' is not assignable to parameter of type 'Params'.
      Object literal may only specify known properties, and 'list_id' does not exist in type 'Params'.

     client.get('lists/members', {list_id: 'test'})

这很有意义,因为https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/twit/index.d.ts文件中没有list_id属性

我做了一些研究并创建了./src/@types/twit.d.ts

import "twit";
declare module 'twit' {
  namespace Twit {
    interface Params {
      list_id?: string;
    }
  }
}

但是我仍然遇到相同的错误。

我的tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist",
    "rootDir": "src",
    "sourceMap": true
  },
  "typeRoots": [
    "src/@types",
    "node_modules/@types"
  ],
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

我正在通过运行代码 ts-node src/index.ts

福特04

您的模块扩充方法通常适用于“标准” npm软件包声明。在的情况下,twit模块增强不幸的是不可能的(或我不知道正确的方式做到这一点)。

Twit通过export = Twit 语法导出为CommonJS模块

默认导出旨在替代此行为;但是,两者是不兼容的。TypeScript支持export =来建模传统的CommonJS和AMD工作流程。

TypeScript显然仅允许ES模块的模块扩充(请参见下面的示例),以上语法显式创建了Node CommonJS默认导出。该Node模块系统实现在某些方面与原始CommonJS标准有所不同,该标准例如用于Babel和TypeScript编译器输出。

例如Node实现允许通过导出单个默认对象modules.exports = ...,而CommonJS规范仅允许向exports对象添加属性和方法,例如export.foo = ...此处此处有关ES和CommonJS模块导入转换的更多信息

tl; dr:我测试了用于Node CommonJS导出的模块扩充(此处忽略模块内部的名称空间,因为它是反模式)。

lib.d.ts:

declare module "twit3" {
  class Twit3 { bar(): string; }
  export = Twit3;
}

index.ts:

import Twit3 from "twit3";

// Error: Cannot augment module 'twit3' because it resolves to a non-module entity.
declare module "twit3" {
  class Twit3 { baz(): string; }
}

密码箱

...没有解决。export =用命名的导出替换语法使示例得以编译(通常不能扩展默认的导出)。

怎么解决呢?

twit如果确实缺少Params选项,请为其创建票证/ PR 同时,这样的解决方法可以保留其他属性的强类型,同时仍向list_id运行时添加选项:

const yourOtherParams: Params = {/* insert here */}
client.get("lists/members", { ...yourOtherParams , ...{ list_id: "123123" } });

// or cast directly
client.get("lists/members", { list_id: "123123" } as Params);

希望能帮助到你!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章