我刚刚花了4个小时排除typescript错误

Object literal may only specify known properties, and 'details'
does not exist in type 'Readonly<{ [x: `details.${string}.value`]:
{ value: string; type: string; } | undefined; [x: `details.${string}.type`]:
{ value: string; type: string; } | undefined;

很明显,无论tsc抱怨什么,我都能在对象中看到"细节".从字面上说,我在同一个文件中有其他函数,但没有typescript错误.

长话短说,Controller将使用单个参数调用Service,其类型在控制器文件上定义,但服务需要知道其获取的数据类型,因此服务文件具有指向控制器的import语句

Controller

import service from './Service'
export type DataType = {...}

const data:DataType = fetch()
service(data)

Service

import DataType from './controller'

export function service(data:DataType) {
  // typescript error
  someOtherFunctionCall<DataType>(data)
}

我认为这是一个非常基本的模式.当我从服务文件中删除import语句时,错误消失了,当然,复制/粘贴了类型定义.奇怪的是,当我粘贴完全相同的行时,错误没有再次出现.这是预期行为吗?我听说nodejs可以处理不太复杂的循环导入.但这种情况发生了,我不应该使用循环进口吗?

100

Category.ts

export default interface Category {
  _id: ObjectId
  details: Record<
    string,
    {
      value: string
      type: string
    }
  >
  ...
}

controller.ts

import { updateItem } from './service'

export interface ScrapItem {
  _id: ObjectId
  details: Record<
    string,
    {
      value: string
      type: string
    }
  >
  ...
}

const item:ScrapItem = scrapSomeItem()
updateItem(item)

service.ts

import Category from 'models/category'
import ScrapItem from './controller'
import db from 'MongodbHelper'

export async function updateItem(item: ScrapItem): Promise<void> {
  const db = await getDb()
  const categoryCollection = db.collection<Category>(category)

  await categoryCollection.updateOne(
    {
      _id
    },
    {
      $set: {
        // THIS IS WHERE I GET ERROR
        // Object literal may only specify known properties, and 'details' does not exist in type ...
        details,
        ...
      }
    },
    {
      upsert: true
    }
  )
}

我在服务中遇到typescript错误.我在这里调用mongodb驱动程序方法updateOne中的一个.这里唯一的解决方法是从const categoryCollection = db.collection<Category>(category)中删除Category,或者在category.ts中添加| anydetails类型定义.

推荐答案

这实际上是一个bug in the mongodb version 4.8个输入声明文件.3天前(2022-07-20),main分支上已修复,但尚未发布.最新版本,即本文 compose 时的4.8版本,来自10 days ago (2022-07-13).

要解决此问题,请将版本降级到4.7:

npm i mongodb@~4.7.0

或者从已安装修复程序的main分支安装:

npm i "https://github.com/mongodb/node-mongodb-native#05e007b0b5ff98151c3ff972ee2f881b4203639e"

Node.js相关问答推荐

使用prisma迁移到SQL失败

Mongoose更新在^8.0.3版中,许多似乎不能按预期工作

如何更改ejs中的镜像src,以防从OMDB API获取的某些镜像具有src=N/A

在Node JS中获取控制台选项卡标题

为什么在导出的函数中调用node-sqlite3中的数据库方法时不起作用?

Express无法发布

无法从MongoDB文档中保存的对象数组中获取对象的属性

仅在一次查询中 MongoDB 上最近的一对位置

如何在nodejs中打印pdf

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

我误解了外键的工作原理吗?使用续集

使用 NPM 三个 mocha+typescript 进行测试

看起来这段代码try GET 请求发送的值变为空白

Axios GET 返回不可读的响应

如何在不全局安装的情况下在 Node REPL 中要求 node 模块?

如何在 node 中找到引用站点 URL?

chart.js 无法创建图表:无法从给定项目获取上下文

如何在 node.js 沙箱中安全地运行用户提交的脚本?

expressjs app.VERB 调用中的 next() 和 next('route') 有什么区别?

NodeJS:如何调试检测到 EventEmitter 内存泄漏.添加了 11 个侦听器