inflearn logo
강의

Course

Instructor

[Code Camp] Highly concentrated backend course created at boot camp

10-03 Product Registration, Lookup API

findOne 타입스크립트오류

Resolved

116

dmb050087997

5 asked

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' 형식에 할당할 수 없습니다.

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

javascript node.js docker rest-api nestjs

Answer 1

0

nwd09074926

안녕하세요! 크하함님!

 

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

image.png

 

윈도우에서 Node js를 설치하고 싶어요

0

16

0

그래프 ql 문서 사용할때 느낌표 남는거 어떻게 없애나요?

0

102

2

강의 전체 소스 코드를 받고싶습니다.

0

93

2

fontawesome 사용 문의

0

96

2

소스 코드 부탁드립니다~

0

99

2

깃 레포지터리 소스

0

96

2

커리큘럼12.css 정렬 에 나오는 과제 정답알고싶어요

0

81

2

10-01 Entity TypeOrmModule.forRoot 에 entities

0

102

3

강의 버전관련 문의입니다

0

111

2

Ubuntu 설치 관련

0

74

1

schema.gql 질문 드립니다.

0

63

1

서버 재실행시 Many to Many

0

120

3

input 관련 문의

0

97

2

Rest API 보다는 graphql이 주된 내용인데

0

145

2

강의 전체 소스코드 받을수있을까요?

0

170

1

도커볼륨 마운트 관련

0

136

2

http => htrtps 호출 인증서 신뢰 오류

0

375

1

self-signed certificate in certificate chain 에러 발생

0

440

1

mongoose 설치 오류

0

149

1

특정 API, 특정 IP 허용 (단일경로에 CORS 활성화)

0

300

2

08-06

0

188

3

구조랑 패턴 관련해서 질문

0

134

2

mydocker

0

135

2

coolsms statuscode 2000 인데 전송안돼는 경우 확인.

0

163

1