web

Typescript - 타입스크립트 자주 발생하는 에러

제이훈 : 세상 모든 지식의 탐구자 2025. 5. 2. 18:14

타입스크립트 자주 발생한 에러들

1. Type 'X' is not assignable to type 'Y'

변수나 함수 인자에 잘못된 타입의 값을 할당했을 때 발생.
let num: number = "hello";
❌ 오류: Type 'string' is not assignable to type 'number'.
✔ 해결: 올바른 타입 사용 또는 as/unknown으로 변환.

2. Property 'X' does not exist on type 'Y'

객체에 존재하지 않는 속성에 접근했을 때 발생.
let user = { name: "Alice" }; console.log(user.age);
❌ 오류: Property 'age' does not exist on type '{ name: string; }'.
✔ 해결: 객체 타입을 올바르게 정의.

3. Argument of type 'X' is not assignable to parameter of type 'Y'

함수에 잘못된 타입의 인자를 전달했을 때 발생.
greet(123);
❌ 오류: Argument of type 'number' is not assignable to parameter of type 'string'.
✔ 해결: 인자의 타입을 함수 선언에 맞게 수정.

4. Object is possibly 'null' or 'undefined'

값이 null 또는 undefined일 가능성이 있을 때 발생.
user.name.length
❌ 오류: Object is possibly 'undefined'.
✔ 해결: 옵셔널 체이닝 user.name?.length 사용.

5. Cannot find name 'X'

선언되지 않은 변수를 사용할 때 발생.
console.log(username);
❌ 오류: Cannot find name 'username'.
✔ 해결: 변수를 사전에 선언.

6. A function whose declared type is 'void' must not return a value

void 함수에서 값을 반환했을 때 발생.
function log(): void { return "hi"; }
❌ 오류: A function whose declared type is 'void' must not return a value.
✔ 해결: 반환 타입 수정 또는 반환 제거.

7. Cannot redeclare block-scoped variable 'X'

let/const로 동일한 변수명을 중복 선언했을 때 발생.
let count = 1; let count = 2;
❌ 오류: Cannot redeclare block-scoped variable 'count'.
✔ 해결: 변수명 변경 또는 scope 분리.

8. Type 'X' is not assignable to type 'never'

never 타입에 다른 값을 할당했을 때 발생.
let neverValue: never = "hello";
❌ 오류: Type 'string' is not assignable to type 'never'.
✔ 해결: never는 도달 불가능한 코드에만 사용.

9. This expression is not callable

함수가 아닌 값을 호출하려 했을 때 발생.
const myFunc: string = "Hello"; myFunc();
❌ 오류: This expression is not callable.
✔ 해결: 타입을 함수로 올바르게 지정.

10. 'X' refers to a value, but is being used as a type here

객체를 타입처럼 사용했을 때 발생.
const User = { name: "Alice" }; let user: User;
❌ 오류: 'User' refers to a value, but is being used as a type here.
✔ 해결: type 또는 interface로 명시적 타입 정의.

#결론
TypeScript에서 자주 발생하는 오류는 대부분 타입 관련 문제로, 정확한 타입 정의와 올바른 타입 변환이 중요.
오류 메시지를 잘 해석하고, 옵셔널 체이닝(?.), as 타입 단언, unknown, never 등을 적절히 사용하면 됨. 귀찮타고 any쓰면 결국엔 업보로 다 돌아옴.