본문 바로가기
TypeScript

[TypeScript] 타입스크립트 타입 추론

by 깅민 2025. 5. 26.

1. 타입 추론

타입 추론이란 타입이 정의되어 있지 않은 변수의 타입을 자동으로 추론하는 것을 말합니다.

 

let str = "str"
console.log(typeof str);
// string 타입으로 추론

 

2. 타입 추론이 가능할 때

2-1. 변수

초기값의 타입으로 추론됩니다.

let no = 10;
console.log(typeof no);
// number 타입으로 추론

 

 

2-2. 구조 분해 할당

let [name, age] = ["a", 20];

console.log(typeof name);
// string 으로 추론
console.log(typeof age);
// number 로 추론

2-3. 함수 반환값

반환값을 기준으로 추론합니다.

function fn() {
  return 20;
}
console.log(typeof fn());
// number로 추론

3. const 상수

const는 리터럴 타입으로 추론됩니다.

const no = 10; // 10 number
const str = "abc"; // "abc" string