【问题标题】:How we should use mongoose with Typescript?我们应该如何在 Typescript 中使用猫鼬?
【发布时间】:2019-08-19 21:21:44
【问题描述】:

我是 typescript 和 express 的新手。 我在 Microsoft Link 的 Typescript Starter 项目中看到了这段代码,我对这段代码的工作原理有点困惑。

例如,'type' 关键字有什么作用? 以及如何在这段代码中使用'&'关键字?

import bcrypt from "bcrypt-nodejs";
import crypto from "crypto";
import mongoose from "mongoose";

export type UserDocument = mongoose.Document & {
    email: string;
    password: string;
    passwordResetToken: string;
    passwordResetExpires: Date;

    facebook: string;
    tokens: AuthToken[];

    profile: {
        name: string;
        gender: string;
        location: string;
        website: string;
        picture: string;
    };

    comparePassword: comparePasswordFunction;
    gravatar: (size: number) => string;
};

type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => {}) => void;

const userSchema = new mongoose.Schema({
    email: { type: String, unique: true },
    password: String,
    passwordResetToken: String,
    passwordResetExpires: Date,

    facebook: String,
    twitter: String,
    google: String,
    tokens: Array,

    profile: {
        name: String,
        gender: String,
        location: String,
        website: String,
        picture: String
    }
}, { timestamps: true });


如果你能解释一下,我真的很感激。

【问题讨论】:

标签: typescript express mongoose


【解决方案1】:

这可能已经回答了好几次了,所以我会简短。

类型

A 类型或 type 就像一个对象的蓝图。最好用一个例子来解释:

如果你有一个名为 Animal 的类型:

type Animal {
  color: string;
}

使用 Animal 键入的对象应包含一个名为 color 的字段,类型为 string

let lion: Animal; 
// the lion object is expected to look like {color: 'some string'} 
// only a object that conforms to Animal can be added to the lion variable.

类型仅此而已,它们只是帮助您控制对象应该做什么以及预期的外观。

查看 typescript 和基本类型的文档here

'&'部分:

假设我们有另一种称为 LeggedAnimal 的类型:

type LeggedAnimal {
  nuberOfLegs: number;  
}

我们可以将两种类型合并为一个新类型。

type Dog = Animal & LeggedAnimal;
// the Dog type is now {color: string, numberOfLegs: number}

“&”将一种或多种类型组合在一起。

【讨论】:

    猜你喜欢
    • 2013-07-10
    • 2012-10-29
    • 2012-10-30
    • 2021-07-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2016-11-21
    相关资源
    最近更新 更多