inflearn logo
강의

講義

知識共有

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

10-03 商品登録、照会 API

findOne 타입스크립트오류

解決済みの質問

109

dmb050087997

投稿した質問数 5

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

回答 1

0

nwd09074926

안녕하세요! 크하함님!

 

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

image.png

 

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

0

83

2

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

0

76

2

fontawesome 사용 문의

0

77

2

소스 코드 부탁드립니다~

0

85

2

깃 레포지터리 소스

0

82

2

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

0

73

2

10-01 Entity TypeOrmModule.forRoot 에 entities

0

85

3

강의 버전관련 문의입니다

0

102

2

Ubuntu 설치 관련

0

61

1

schema.gql 질문 드립니다.

0

51

1

서버 재실행시 Many to Many

0

101

3

input 관련 문의

0

90

2

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

0

130

2

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

0

155

1

도커볼륨 마운트 관련

0

127

2

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

0

350

1

self-signed certificate in certificate chain 에러 발생

0

413

1

mongoose 설치 오류

0

142

1

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

0

281

2

08-06

0

178

3

구조랑 패턴 관련해서 질문

0

125

2

mydocker

0

128

2

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

0

156

1

싸이월드 과제 쪽이 궁금합니다.

0

147

2