Reputation: 110
I'm new to typescript and express . I saw this code on Typescript Starter project by microsoft Link and I'm a little confused about how this code works .
for example what does the 'type' keyword do? and how the '&' keyword in used in this code ?
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 });
I really appreciate if you could explain it a bit .
Upvotes: 0
Views: 120
Reputation: 26
This has probably been answered more than a couple of times so I will be brief.
A Type or type is like a blue-print for an object. Best to explain it with a example:
If you have a type called Animal:
type Animal {
color: string;
}
Objects that is typed with Animal is expected to include a field called color
of type 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.
Types are nothing more than that, they just help you to control what an object should do and what it is expected to look like.
Checkout the documentation for typescript and basic types here
Let's say we have another type called LeggedAnimal:
type LeggedAnimal {
nuberOfLegs: number;
}
We can combine two types to merge with a new type.
type Dog = Animal & LeggedAnimal;
// the Dog type is now {color: string, numberOfLegs: number}
The '&' combines one or more types together.
Upvotes: 1