TypeScript 中的静态
¥Statics in TypeScript
要使用 Mongoose 的自动类型推断来定义 statics 和 methods 的类型,你应该使用 methods
和 statics
结构选项定义方法和静态,如下所示。请勿使用 Schema.prototype.method()
和 Schema.prototype.static()
函数,因为 Mongoose 的自动类型推断系统无法检测使用这些函数定义的方法和静态变量。
¥To use Mongoose's automatic type inference to define types for your statics and methods, you should define your methods and statics using the methods
and statics
schema options as follows.
Do not use the Schema.prototype.method()
and Schema.prototype.static()
functions, because Mongoose's automatic type inference system cannot detect methods and statics defined using those functions.
const userSchema = new mongoose.Schema(
{ name: { type: String, required: true } },
{
methods: {
updateName(name: string) {
this.name = name;
return this.save();
}
},
statics: {
createWithName(name: string) {
return this.create({ name });
}
}
}
);
const UserModel = mongoose.model('User', userSchema);
const doc = new UserModel({ name: 'test' });
// Compiles correctly
doc.updateName('foo');
// Compiles correctly
UserModel.createWithName('bar');
使用泛型
¥With Generics
我们建议尽可能使用 Mongoose 的自动类型推断,但你可以使用 Schema
和 Model
泛型为你的静态和方法设置类型推断。Mongoose models 没有 statics 的显式通用参数。如果你的模型有静态,我们建议创建一个 extends Mongoose 的 Model
接口的接口,如下所示。
¥We recommend using Mongoose's automatic type inference where possible, but you can use Schema
and Model
generics to set up type inference for your statics and methods.
Mongoose models do not have an explicit generic parameter for statics.
If your model has statics, we recommend creating an interface that extends Mongoose's Model
interface as shown below.
import { Model, Schema, model } from 'mongoose';
interface IUser {
name: string;
}
interface UserModelType extends Model<IUser> {
myStaticMethod(): number;
}
const schema = new Schema<IUser, UserModelType>({ name: String });
schema.static('myStaticMethod', function myStaticMethod() {
return 42;
});
const User = model<IUser, UserModelType>('User', schema);
const answer: number = User.myStaticMethod(); // 42
你应该将方法作为第三个通用参数传递给 Schema
构造函数,如下所示。
¥You should pass methods as the 3rd generic param to the Schema
constructor as follows.
import { Model, Schema, model } from 'mongoose';
interface IUser {
name: string;
}
interface UserMethods {
updateName(name: string): Promise<any>;
}
const schema = new Schema<IUser, Model<IUser>, UserMethods>({ name: String });
schema.method('updateName', function updateName(name) {
this.name = name;
return this.save();
});
const User = model('User', schema);
const doc = new User({ name: 'test' });
// Compiles correctly
doc.updateName('foo');