【问题标题】:Why isn't my MongoDB ObjectID recognised as a type in TypeScript?为什么我的 MongoDB ObjectID 没有被识别为 TypeScript 中的类型?
【发布时间】:2019-05-27 05:22:16
【问题描述】:

我将 Node.js 与 MongoDB 和 TypeScript 一起使用。

以下两行代码:

const ObjectID = require("mongodb").ObjectID;
const id = new ObjectID("5b681f5b61020f2d8ad4768d");

编译没有错误。

但是当我将第二行改为:

const id: ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");

我收到一个错误:

找不到名称“ObjectID”

为什么 ObjectID 在 TypeScript 中不被识别为类型?

【问题讨论】:

    标签: node.js mongodb typescript


    【解决方案1】:

    对于新版本,请改为:

    import { ObjectId } from 'bson';

    【讨论】:

      【解决方案2】:
      1. yarn add @types/mongodb
      2. 使用导入import {ObjectID} from 'mongodb';

      现在使用 ObjectID 作为类型就足够了。

      【讨论】:

      • 即使使用@types,我也会得到error TS2348: Value of type 'typeof ObjectId' is not callable. Did you mean to include 'new'?。 tsconfig 中是否需要特殊设置?
      • @RomanMik,改为这样做import { ObjectId } from 'bson';
      • warning @types/mongodb@4.0.7: mongodb provides its own types. @types/mongodb is no longer needed.
      【解决方案3】:

      即使安装了类型,typescript 也不会正确输入require("mongodb").ObjectId。您需要使用 require 作为导入的一部分:

      import mongodb = require("mongodb");
      const ObjectID = mongodb.ObjectID;
      const id: mongodb.ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");
      

      如果你想坚持原来的版本,你必须意识到你不是在导入类型,你只是在导入构造函数。有时类型和值具有相同的名称并一起导入,给人一种相同的错觉,但实际上类型和值存在于不同的宇宙中。您可以声明关联类型并从模块类型中获取:

      const ObjectID = require("mongodb").ObjectID;
      type ObjectID= typeof import("mongodb").ObjectID;
      const id: ObjectID = new ObjectID("5b681f5b61020f2d8ad4768d");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-22
        • 2020-11-03
        • 1970-01-01
        • 1970-01-01
        • 2019-03-24
        • 2022-07-11
        • 2021-04-13
        • 1970-01-01
        相关资源
        最近更新 更多