TypeScript-섹션3. 타입스크립트 이해하기- 타입 추론(6)

손주완·2025년 7월 9일

TypeScript Section3

목록 보기
5/8

1. 타입 추론이란

타입이 정의되어 있지 않은 변수의 타입을 자동으로 추론.
(타입 추론이 불가능한 변수(ex 매개변수)에는 암시적으로 any 타입이 추론)
"strict": ture 설정시, 타입추론이 불가능한 변수의 암시적 any 타입은 오류.

2. 타입 추론이 가능한 상황들

1) 변수 선언

let a = 10;
// number 타입으로 추론

let b = "hello";
// string 타입으로 추론

let c = {
  id: 1,
  name: "이정환",
  profile: {
    nickname: "winterlood",
  },
  urls: ["https://winterlood.com"],
};
// id, name, profile, urls 프로퍼티가 있는 객체 타입으로 추론

2) 구조 분해 할당

let { id, name, profile } = c;

let [one, two, three] = [1, "hello", true];

3) 함수의 반환값

function func() {
  return "hello";
}
// 반환값이 string 타입으로 추론된다

4) 기본값이 설정된 매개변수

function func(message = "hello") {
  return "hello";
}

**주의해야 할 상황들
1. 암시적 any타입 추론
-> 변수 선언시 초기값 생략. (strict도 오류로 판단x)
2. const 상수의 추론
-> 리터럴 타입으로 추론.(값 변경x이므로)

const num = 10;
// 10 Number Literal 타입으로 추론

const str = "hello";
// "hello" String Literal 타입으로 추론

3. 최적 공통 타입

다양한 타입의 요소를 담은 배열을 초기값으로 설정시, 최적으로 추론

let arr = [1, "string"];
// (string | number)[] 타입으로 추론

0개의 댓글