Typescript-无法扩充模块

问题描述 投票:1回答:1

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

我还从@types/twit安装了https://www.npmjs.com/package/@types/twit

我想向'lists/members'端点发出请求。

我的代码是:

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运行代码

node.js typescript twitter
1个回答
1
投票

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

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

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

tl; dr:

我测试了Node CommonJS导出的模块增强(此处忽略了模块内部的名称空间,因为它是anti-pattern)。

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; } }

Codesandbox

...没有解决。用命名的导出替换export =语法使示例得以编译(通常为默认导出cannot be augmented)。

如何解决?

如果确实缺少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);

希望,有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.