李恒道 发表于 2023-1-4 23:32:35

nestjs mongoose使用raw函数与ts类型声明与class声明区别

# 结论
如果使用ts类型声明,但不使用raw函数
则等同于在ts类型推断存在Student,而实际类型为Object类型
```js
interface Student {
name: string;
age: number;
}

@Schema()
export class Cat {
@Prop()
name: string;

@Prop()
age: number;

@Prop()
breed: string;

@Prop()
stu: Student;
}
```
如果使用Class类,同时不使用raw函数
则等同于声明了TS类型声明,并且JS存在对应的类型
```js
@Schema()
export class Student2 {
@Prop()
name: string;

@Prop()
age: number;
}
@Schema()
export class Cat {
@Prop()
name: string;

@Prop()
age: number;

@Prop()
breed: string;

@Prop()
stu: Student2;
}
```
如果使用TS类型声明+raw函数
则类型推断以TS类型声明为主,实际生成的代码以raw函数内容为主
```js
interface Student {
name: string;
age: number;
}
@Schema()
export class Cat {
@Prop()
name: string;

@Prop()
age: number;

@Prop()
breed: string;

@Prop(
    raw({
      name: { type: String },
      age: { type: Number },
    }),
)
stu: Student;
}
```
页: [1]
查看完整版本: nestjs mongoose使用raw函数与ts类型声明与class声明区别