웹사이트 검색

typescript - Nestjs 타입세이프 mongoose, 모델 함수가 올바른 타입을 요구하지 않음 (any)


슈마 인터페이스

export interface MyCat {
  name: string;
  color: string;
}

export type Cat = MyCat & Document;

export const CatSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  color: {
    type: String,
    required: true,
  }
});

해당 함수가 받는 Dto(색상 속성이 없다는 점에 유의)

export class CreateCatDto {
  @IsString()
  readonly name: string = 'Franco';
}

함수가 호출되면, 새로운 Cat(cat)에서는 오류가 없지만, mongoose에서는 필요한 속성이 없다는 런타임 오류를 발생시킵니다

  constructor(@InjectModel('Cat') private readonly catModel: Model<Cat>) {}

  async create(cat: CreateCatDto) {
    // typescript should give me an error here :(
    const createdCat = new this.catModel(cat);
    return await createdCat.save();
  }

제 질문은, 모델 함수들이 무엇을 정확히 받아야 하는지 이해하도록 어떻게 해야 하는가입니다? 제가 보기에는 이 함수들이 종종 any 타입을 받는 것 같습니다.

답변 #1

타입세이프 모델링을 위해 Typegoose https://typegoose.github.io/typegoose/ 을 사용할 수 있습니다