dev.syw
TypeScript

TS: Type 'X' is not assignable to type 'Y' 해결

Type 'string' is not assignable to type 'number'

#TypeScript#타입오류#타입좁히기#제네릭

증상

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

원인

대입하려는 값의 타입이 받는 쪽 타입과 호환되지 않습니다. 특히 undefined/null이 섞인 경우(string | undefinedstring)가 가장 흔합니다.

해결

1) 값 타입을 실제 의도에 맞추기

const age: number = Number(input.value); // string → number 변환

2) undefined/null 좁히기(narrowing)

function show(name?: string) {
  if (!name) return;        // 여기서 undefined 제거
  const len: number = name.length; // name은 이제 string
}

기본값이나 옵셔널 체이닝도 유효합니다.

const name: string = maybe ?? '익명';

3) 유니온은 타입 가드로 분기

function fmt(v: string | number) {
  return typeof v === 'number' ? v.toFixed(2) : v.toUpperCase();
}

4) 정말 확실할 때만 타입 단언(as)

const el = document.getElementById('app') as HTMLDivElement;

as는 컴파일러 검사를 끄는 것이라 틀리면 런타임 오류로 이어집니다. 가능하면 타입 가드(조건문)로 좁히는 편이 안전합니다. 기본 타입 문법은 TypeScript 타입 치트시트를 참고하세요.

← 에러 해결 모음으로 돌아가기