使用TypeScript时是否需避免循环导入?附报错场景分析
TypeScript循环导入导致的MongoDB更新类型错误
报错信息
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;
我花了4小时排查这个TypeScript错误,明明能看到对象里存在details字段,且同文件内其他函数都未出现该错误。
问题源于循环导入:Controller调用Service并传入参数,参数类型定义在Controller文件中,Service为获取类型导入该文件,形成循环依赖。
简化的循环导入场景
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) }
我原本以为这是基础的代码模式,删除Service里的导入语句、复制类型定义后错误消失,但重新粘贴导入语句后错误又未重现。我知道Node.js可处理简单循环导入,但这次出了问题,到底该不该避免循环导入?
项目实际代码
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: { // 此处触发错误 // Object literal may only specify known properties, and 'details' does not exist in type ... details, ... } }, { upsert: true } ) }
临时解决方案
目前找到的临时解决办法:移除Category泛型,或者给details添加| any类型。
内容的提问来源于stack exchange,提问作者swimming_polar
相关产品推荐
相关产品推荐

