![](/img/trans.png)
[英]How to resolve - Argument of type is not assignable to type - TYPESCRIPT
[英]TypeScript: Argument of type is not assignable
TypeScript新手在這里遷移現有項目。 我們有貓鼬模型,其外觀類似於以下代碼片段,並使用discriminatorKey
屬性:
const task = new mongoose.Schema({
name: {
type: String
},
notes: {
type: String
}
}, {
discriminatorKey: 'type',
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
這在編譯期間給我以下錯誤:
src/models/task.ts(12,3): error TS2345: Argument of type '{ discriminatorKey: string; }' is not assignable to parameter of type 'SchemaOptions'.
Object literal may only specify known properties, and 'discriminatorKey' does not exist in type 'SchemaOptions'.
我正在使用這些@types定義,這似乎是最新的定義:
"@types/mongoose": "^4.7.8"
我知道類型定義沒有指定discriminatorKey
(在查看node_modules/@types/mongoose/index.d.ts
時顯然可見),但是我不理解(a)為什么(監督?其他版本?其他)原因?),(b)如何避免該錯誤?
(c)額外的問題: @types
定義的版本控制策略對我來說仍然不清楚。 我認為類型定義應該與實際庫的版本匹配,但是,通常似乎沒有匹配的版本-例如,我們使用的是express
版本。 4.13.4,但沒有匹配的@types/express
版本。 在這種情況下,最佳做法是什么?
我有點遲了,但是我遇到了同樣的問題。 我正在使用@types/mongoose
4.7.12
並且尚未更新。
作為臨時解決方案,當您遇到此類問題時,有兩種選擇:
🤦將整個問題對象投射到any
對象
內聯定義選項時,可以將它們強制轉換為any
:
const task: mongoose.Schema = new mongoose.Schema({ ... }, {
discriminatorKey: 'type',
...
} as any);
要么
const task: mongoose.Schema = new mongoose.Schema({ ... }, <any> {
discriminatorKey: 'type',
...
});
這種方法的缺點是,現在將對所有屬性禁用對該SchemaOptions
對象的類型檢查,因此,如果您鍵入toJSON
,而鍵入toJSNO
,則TypeScript
將不會警告您。
👌將有問題的對象強制轉換為使用未知屬性的語句中的any
對象
一種不同的方法,以保持類型檢查的已知特性工作,但禁用它的未知的人是定義選項之前,對象與已知的特性,並添加未知的以后他們鑄造any
:
const options: mongoose.SchemaOptions = {
toObject: { virtuals: true },
toJSON: { virtuals: true },
};
(options as any).discriminatorKey = 'type';
// or (<any> options).discriminatorKey = 'type';
const task = new mongoose.Schema({ ... }, options);
🙏旁注:請貢獻!
如果您在此軟件包或以后的任何其他軟件包中發現任何類似的問題,則這是一個非常簡單且最小的更改,您可以修復並將PR更改為DefinitelyTyped 。 實際上,對於這樣的事情,您甚至不需要克隆存儲庫,我只需要使用GitHub中的“編輯”按鈕就可以做到。
這是PR: https : //github.com/DefinitelyTyped/DefinitelyTyped/pull/16598 ,一旦合並,只需更新到最新版本即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.