如果我在創建新模式之前將 mongoose 模式描述物件存盤在變數中,它將不會選擇正確的模式選項。例如:
const person = {
name: { type: String, required: true }
};
const PersonSchema = new Schema(person);
type Person = InferSchemaType<typeof PersonSchema>;
Person
現在的型別是:
type Person = {
name?: string;
}
錯誤地將欄位標記name
為可選。
但是當我做看似幾乎完全相同的事情時:
const PersonSchema = new Schema({
name: { type: String, required: true }
});
type Person = InferSchemaType<typeof PersonSchema>;
Person
現在的型別是:
type Person = {
name: string;
}
按要求正確name
標記。
我真的不知道為什么會這樣。
誰能解釋一下?謝謝!
Codesandbox 鏈接:https ://codesandbox.io/s/fancy-cdn-kx378p?file=/index.js
uj5u.com熱心網友回復:
我想我只是在多擺弄之后回答了自己。
它更像是打字稿而不是貓鼬。
它基本上正在發生,因為如果我這樣定義我的物件:
const person = {
name: { type: String, required: true }
};
該物件仍然是可變的,因此打字稿不會假設person.name
它具有任何價值,因此本質上使這個道具name
成為string | undefined
可選的。
解決方案是告訴 typescript 編譯器,這個物件不會通過添加as const
.
這將正常作業:
const person = {
name: { type: String, required: true }
} as const;
const PersonSchema = new Schema(person);
type Person = InferSchemaType<typeof PersonSchema>;
結果是:
type Person = {
name: string;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506443.html