강의

멘토링

커뮤니티

Inflearn コミュニティ Q&A

dmb050087997 のプロフィール画像
dmb050087997

投稿した質問数

[コードキャンプ]ブートキャンプで作られた高濃縮バックエンドコース

10-03 商品登録、照会 API

findOne 타입스크립트오류

解決済みの質問

作成

·

98

0

 

import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Product } from './entities/product.entity';
import { InjectRepository } from '@nestjs/typeorm';
import {
  IProductServiceCreate,
  IProductServiceFindOne,
} from './interfaces/products-service.interface';

@Injectable()
export class ProductsService {
  constructor(
    @InjectRepository(Product)
    private readonly productsRepository: Repository<Product>,
  ) {}

  findAll(): Promise<Product[]> {
    return this.productsRepository.find();
  }

  findOne({ productId }: IProductServiceFindOne): Promise<Product> {
    // @ts-ignore
    return this.productsRepository.findOne({ where: { id: productId } });
  }

  create({ createProductInput }: IProductServiceCreate): Promise<Product> {
    const result = this.productsRepository.save({
      ...createProductInput,
      // 하나하나 직접 나열하는 방식
      // name: '마우스',
      // description: '좋은 마우스',
      // price: 3000,
    });
    return result;
  }
}

이코드가 제코드인데 findOne 메서드에서 // @ts-ignore를 하지 않으면

Promise<Product | null>' 형식은 'Promise<Product>' 형식에 할당할 수 없습니다.
'Product | null' 형식은 'Product' 형식에 할당할 수 없습니다.
'null' 형식은 'Product' 형식에 할당할 수 없습니다.

라는 에러가 뜹니다 어떻게 해야하나요?

javascriptnode.jsdockerrest-apinestjs

回答 1

0

nwd09074926님의 프로필 이미지
nwd09074926
インストラクター

안녕하세요! 크하함님!

 

데이터를 조회 해봤더니 없을 수도 있으므로, Product객체가 아닌 null이 될 가능성도 있어요!
따라서, 최종 리턴타입에 Promise<Product> 부분에 Promise<Product | null> 을 추가해 주세요!

image.png

 

dmb050087997 のプロフィール画像
dmb050087997

投稿した質問数

質問する