본문 바로가기
Random

Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345)

by SeanK 2022. 5. 14.

오늘 algolia 환경설정 코드를 작성하다가 아래와 같은 에러코드를 만났다.

 

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.   Type 'undefined' is not assignable to type 'string'.ts(2345)

 

사실 여러 번 봐왔던 오류코드라 대충 짐작이 왔다. 

타입 설정 문제였다. 

 

문제가 생긴 코드는 아래와 같다.

 

const algoliaClient = algolia(process.env.REACT_APP_ALGOLIA_appId, process.env.REACT_APP_ALGOLIA_apiKey);

 

process.env에는 string 혹은 undefined의 값이 들어올 수 있지만 algolia() 메서드에서는 string만을 받도록 설정되어 있어 발생한 문제였다. 

 

따라서 아래와 같이 코드를 변경해 오류를 해결했다.

 

let appId: string = process.env.REACT_APP_ALGOLIA_appId || '';
let apiKey: string = process.env.REACT_APP_ALGOLIA_apiKey || '';
const algoliaClient = algolia(appId, apiKey);