如果在创建新模式之前将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
我想我只是在多摆弄了一番之后才回答了自己。
与其说是猫鼬,不如说是打字。
这基本上是因为如果我这样定义我的对象:
const person = {
name: { type: String, required: true }
};
该对象仍然是可变的,因此typescript不会假设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;
}