TypeScript引用了非静态方法

时间:2019-06-01 16:08:01

标签: javascript typescript

我需要从根目录加载模块,因此我正在使用require.main.require()进行加载。由于导入无法访问根目录,因此需要使用require。但是,这引用了错误的connect()方法:

export class MongoClient extends EventEmitter {
  connect(callback: MongoCallback<MongoClient>): void;
}

我需要的是它引用静态方法:

export class MongoClient extends EventEmitter {
  static connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
}

使用node编译和执行时,代码运行良好,只是在编辑器中显示错误。这就是我正在做的:

declare type MongoClient = import('mongodb').MongoClient

const mongo = require.main && require.main.require('mongodb')
const MongoClient: MongoClient = mongo.MongoClient

async function connect() {
  let url = 'mongodb://....' 
  await MongoClient.connect(url, { useNewUrlParser: true })
}
  

预期0-1个参数,但得到2个。

2 个答案:

答案 0 :(得分:0)

问题在于,打字稿期望在变量上调用connect时调用成员函数,但是类型声明将connect指定为静态。

由于必须通过require.main进行导入,这导致实例而不是静态类,因此最简单的解决方法是将connect重新声明为实例成员。

import { MongoClient, MongoClientOptions} from "mongodb";

declare class MyMongoClient extends MongoClient {
  connect(uri: string, options?: MongoClientOptions): Promise<MongoClient>;
  connect(): Promise<MongoClient>;
}

const mongo = require.main && require.main.require('mongodb')
const mongoClient = mongo.MongoClient  as MyMongoClient

async function connect() {
  let url = 'mongodb://....'
  await mongoClient.connect(url, { useNewUrlParser: true })
}

由于使用了define关键字,实际的模块在编译后将不会被拉入。

答案 1 :(得分:0)

看起来解决方法是在声明typeof时只使用type关键字和联合类型。

declare type MongoClient = typeof import('mongodb').MongoClient | import('mongodb').MongoClient