728x90
728x90
환경 변수 타입 설정하기
들어가며
- 타입스크립트에서 환경 변수(Environment Variable)에 타입 오류가 발생하지 않도록 타입을 설정하는 방법을 정리해본다.

방법
- 다음과 같은 환경 변수 파일이 있다고 해보자.
- 이제 이 환경 변수를 프로젝트 내의 다른 파일에서 불러와서 사용해볼 것이다. (Next.js 프레임워크 사용)
.env.local
NEXT_PUBLIC_API_KEY="="***********" NEXT_PUBLIC_SPACE_ID="**************************"
(1) !
(Non-Null Assertion) 연산자 사용하기
!
를 사용하여 값이undefined
가 아님을 타입스크립트에 명시한다.- 하지만 이 방법은 해당 환경 변수가 존재하지 않을 경우, 런타임 에러가 발생한다는 단점이 있다.
const client = createClient({ space: process.env.NEXT_PUBLIC_SPACE_ID!, environment: 'master', accessToken: process.env.NEXT_PUBLIC_API_KEY!, });
!
연산자는 해당 값이Null
또는undefined
가 아니라는 것을 타입스크립트 컴파일러에게 명시적으로 알려준다.
(2) throw
를 사용하여 안전하게 타입 검증하기
- 환경 변수가 설정되지 않은 경우, 명시적으로 에러를 발생시켜 런타임 에러를 방지할 수 있다.
- 환경 변수의 존재 여부를 명확하게 확인할 수 있지만, 코드가 다소 길어진다는 단점이 있다.
const getEnvVar = (key: string): string => { const value = process.env[key]; if (!value) { throw new Error(`환경 변수 존재하지 않음 : ${key}`); } return value; }; // 클라이언트 생성하기 const client = createClient({ space: getEnvVar('NEXT_PUBLIC_SPACE_ID'), environment: 'master', accessToken: getEnvVar('NEXT_PUBLIC_API_KEY'), });
(3) dotenv
와 타입 정의 추가하기
- 환경 변수에 대한 타입 정의를 추가하여 타입스크립트가 변수가 존재한다는 것을 보장하게 할 수 있다.
- 타입 안정성이 향상되지만,
env.d.ts
파일을 따로 추가해줘야 한다.
/.env.d.ts
declare namespace NodeJS { interface ProcessEnv { NEXT_PUBLIC_SPACE_ID: string; NEXT_PUBLIC_API_KEY: string; } }
(4) 환경 변수의 기본값 설정하기
- 환경 변수의 기본값을 설정하여
undefined
인 경우에도 동작하도록 한다. - 환경 변수가 없을 때, 빈 문자열이 값이 되어 빈 문자열로 동작해 오류를 쉽게 놓칠 수 있다.
const client = createClient({ space: process.env.NEXT_PUBLIC_SPACE_ID ?? '', environment: 'master', accessToken: process.env.NEXT_PUBLIC_API_KEY ?? '', });
안정성과 가독성을 고려한다면, 방법 2와 방법 3을 사용하는 것이 좋다.
참고 사이트
Define types for process.env in TypeScript
TypeScript is a superset of JavaScript and is designed to make development easier and more efficient. One of the ways it does this is by providing type checking, which helps prevent errors and makes…
medium.com
Documentation - TypeScript 2.0
TypeScript 2.0 Release Notes
www.typescriptlang.org
728x90
728x90
'Programming > TypeScript' 카테고리의 다른 글
[TypeScript] 클래스(Class) (0) | 2024.10.12 |
---|---|
[TypeScript] 제네릭(Generic) (0) | 2024.10.12 |
[TypeScript] 인터페이스(Interface) (0) | 2024.10.12 |
[TypeScript] Zod 라이브러리 (0) | 2024.10.11 |
[TypeScript] 타입 가드(Type Guard) (0) | 2024.10.10 |
[TypeScript] 모듈 방식 사용하기 (0) | 2024.10.10 |
[TypeScript] 인터페이스(Interface)와 타입 별칭(Type Alias) 비교 (0) | 2024.10.09 |
[TypeScript] ! 연산자(Non-null Assertion Operator) (0) | 2024.08.20 |