我刚刚花了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
中添加| any
到details
类型定义.