为什么使用存储在变量中的模式创建的猫鼬模式看不到所需的标志?



如果在创建新模式之前将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;
}

最新更新