프론트엔드/TypeScript, Next.js

Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.

anott 2022. 5. 6. 09:57

Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.

위의 에러가 여러 상황에서 발생했다.

 

 

 

1. 아래처럼 string 타입이 분명 들어오게 해놨는데 데이터를 이용하려 할 때 위의 에러가 발생하는 경우가 있다.

interface StoreDataType {
  place_id: string;
}

이 때는 아래처럼 !를 끝에 붙여서 해결했다.

place_id: results[i].place_id!,

 

 

2. Next.js를 이용해서 구현하는 과정에서 .env 안 process.env.NEXT_PUBLIC_GOOGLE_KEY를 사용하려는데 에러가 발생한 경우였다. 값은 무조건 string일수밖에 없는데 이렇게 에러가 발생한 경우는 process.env.NEXT_PUBLIC_GOOGLE_KEY를 바로 사용하지 않고 새 변수(아래 코드에서는 googleKey)를 이용하는 방법이 최선인 것 같다. 이때 해결 방법은 세 가지 정도가 있다.

// 해결 방법 1
const googleKey: string = process.env.NEXT_PUBLIC_GOOGLE_KEY ?? '';

// 해결 방법 2
const googleKey: string = process.env.NEXT_PUBLIC_GOOGLE_KEY || '';

// 해결 방법 3
const googleKey: string = process.env.NEXT_PUBLIC_GOOGLE_KEY as string;

 

 

 

https://stackoverflow.com/questions/54496398/typescript-type-string-undefined-is-not-assignable-to-type-string 이곳에서 해결 방법을 찾았다.