我有一个
Survey
型号:
@Table
export class Survey extends Model {
@PrimaryKey
@Default(DataType.UUIDV4)
@Column(DataType.UUID)
id: string;
@Column({ type: DataType.STRING, allowNull: false })
name: string;
@Column({ type: DataType.STRING, defaultValue: '', allowNull: false })
description: string;
@Column({ type: DataType.BOOLEAN, defaultValue: false, allowNull: false })
isActive: boolean;
}
插入调查时,仅需要
name
字段。其余的都有默认值。
这是我的
CreateSurveyDto
:
import { IsString } from 'class-validator';
export class CreateSurveyDto {
@IsString()
name: string;
@IsString()
description?: string;
}
问题是,在我的服务中,当将 dto 作为参数传递给 create 函数时,我遇到了 TypeScript 错误:
public async createSurvey(createSurveyDto: CreateSurveyDto): Promise<Survey> {
return await this.surveyModel.create(createSurveyDto);
}
这会导致错误:
Argument of type 'CreateSurveyDto' is not assignable to parameter of type 'Optional<any, string>'.
Type 'CreateSurveyDto' is not assignable to type 'Omit<any, string>'.
Index signature for type 'number' is missing in type 'CreateSurveyDto'
我在这里做错了什么?在 dto 中,创建调查时仅需要
name
,但用户可以根据需要选择传递描述。我应该包含模型中的所有字段并设置一些可选字段吗?
我发现解决这个问题的方法是这样做:
return await this.surveyModel.create({ ...createSurveyDto, isActive: true });
通过将 DTO 属性传播到新对象中,您实际上是在创建一个新的对象文字,TypeScript 可以将其理解为 create 方法的有效参数。