본문 바로가기
Q&A해결2025년 2월 3일1분 읽기

TypeScript에서 as const 쓰면 타입이 너무 좁아져서 함수 인자로 못 넘깁니다

데
데이터사이언스현
조회 851댓글 2

객체에 as const를 붙이면 리터럴 타입이 되어서 함수 인자로 넘길 때 타입 에러가 발생합니다.

const config = { mode: 'production' } as const
function init(opts: { mode: string }) { ... }
init(config) // Error: 'production' is not assignable to string

댓글 2

김김영삼1년 전

as const로 선언하면 'production' 리터럴 타입이 됩니다. 해결 방법:

// 방법 1: 함수 파라미터를 리터럴 유니온으로
function init(opts: { mode: 'production' | 'development' }) { }

// 방법 2: satisfies 사용 (TypeScript 4.9+)
const config = { mode: 'production' } satisfies { mode: string }

// 방법 3: readonly 제거
init(config as { mode: string })

satisfies가 가장 권장됩니다. 타입 검증하면서 추론도 유지합니다.

데데이터사이언스현1년 전
정리가 너무 깔끔해요. 북마크했습니다. 감사합니다!
Ctrl+Enter로 등록