了解 Type assertions/casting 周围的 Typescript 语法

Understand Typescript syntax around Type assertions/casting

我是 TypeScript 的新手。

我一直在寻找优雅的模式来使用 TypeScript 定义 Mongoose 模式。我一直在研究 Nicholas Mordecai 的一篇文章:

https://know-thy-code.com/mongoose-schemas-models-typescript/

非常有帮助(感谢 Nicholas)!尽管有一些我无法深入了解的编码约定。第一个涉及以下代码块...

import { Schema, model, Document, Model } from 'mongoose';

declare interface IContact extends Document{
    name: string;
    email: string;
    phone?: string;
    message?: string;
    course_enquiry?: string;
    creation_date: Date;
}

export interface ContactModel extends Model<IContact> {};

让我困惑的具体一点是:

 "Model<IContact> {};"

当然,我什至无法查看生成的 js 代码,因为接口未被转译。

ContactModel 扩展了 IContact,但仅在 IContact 已 re-asserted/cast(从 Mongoose 文档)到 Mongoose 模型之后。我在这里假设正确吗?难倒我的只是代码约定...

"Class<interface> {};"

实际上 does/achieves!

第二个问题与以下代码有关,Nicholas 已将其包含在与上述相同的 ts 文件中:

export class Contact {

    private _model: Model<IContact>;

    constructor() {
        const schema =  new Schema({
            name: { type: String, required: true },
            email: { type: String, required: true },
            phone: { type: String },
            message: { type: String },
            course_enquiry: { type: String },
            creation_date: { type: Date, default: Date.now }
        });

        this._model = model<IContact>('User', schema);
    }

    public get model(): Model<IContact> {
        return this._model
    }
}

我希望在这里提供帮助的一点是评估员获取方法...

public get model(): Model<IContact> {
        return this._model
}

我理解get assessors的原理,但我不确定“model():”之后的代码返回的是函数还是this._model的实例(或两者)?

另外,在一个单独的ts控制器文件中,尼古拉斯使用以下两段代码来使用上面的...

import { connect, connection, Connection } from 'mongoose';
import { Contact, ContactModel } from './../models/contactsModel';

declare interface IModels {
    Contact: ContactModel;

}
        this._models = {
            Contact: new Contact().model
            // this is where we initialise all models
        }

注意。 this._models 被定义为“private _models: IModels;”

我真的很想具体详细地了解这段代码的作用!我的解释是,正在创建一个新的 Contact 对象,然后使用 get assessor 方法 model(),其中 returns 一个 IContact 接口(cast/asserted 作为模型)??

非常感谢任何帮助!!

非常感谢。

Model<IContact> 中,您看到 通用 Class。 请参阅有关它们的文档 here

In languages like C# and Java (and tsc) , one of the main tools in the toolbox for creating reusable components is generics, that is, being able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types.

A generic class has a similar shape to a generic interface. Generic classes have a generic type parameter list in angle brackets (<>) following the name of the class.

Just as with interface, putting the type parameter on the class itself lets us make sure all of the properties of the class are working with the same type.