Web/TypeScript

[TS] 타입스크립트 이해하기 - 대수 타입, 타입 추론

ansui 2024. 11. 14. 15:13

대수 타입

여러 개의 타입을 합성해서 새롭게 만들어낸 타입.
합집합 타입교집합 타입이 존재한다.

 

1️⃣ 합집합 타입 (Union 타입)

// 합집합 타입 (Union 타입)
let a: string | number | boolean; // 추가할 수 있는 타입의 개수는 무한대
a = 1;
a = "hello";

let arr: (number | string | boolean)[] = [1, "hello", true];

type Dog = {
  name: string;
  color: string;
};

type Person = {
  name: string;
  language: string;
};

type Union1 = Dog | Person;

let union1: Union1 = {
  name: "",
  color: "",
};

let union2: Union1 = {
  name: "",
  language: "",
};

let union3: Union1 = {
  name: "",
  color: "",
  language: "",
};

// 오류 발생
let union4: Union1 = {
    name: "", 
}

 

2️⃣ 교집합 타입 (Intersection 타입)

// 교집합 타입 (Intersection 타입)
let variable: number & string;

type Dog1 = {
  name: string;
  color: string;
};

type Person1 = {
  name: string;
  language: string;
};

type Intersection = Dog1 & Person1;
let intersection: Intersection = {
  name: "",
  color: "",
  language: "",
};


타입 추론

굳이 타입을 일일히 적지 않아도 된다. - 모든 상황에 적용되는 것은 x

 

변수 - 초기값을 기준으로 추론

함수 - 반환값을 기준으로 추론

함수의 매개변수 - 초기값을 기준으로 추론

타입 넓히기 - 웬만하면 자동으로 추론하고 const가 아니라면 타입을 넓혀서 범용적으로 사용할 수 있도록 추론해준다.

// 매개변수가 있는 함수에서 매개변수의 타입을 정의하지 않으면 오류 발생
function func(param){}

// 타입 추론이 가능한 상황 - 변수의 초기값을 기준으로 추론
let a = 10;
let b = "hello";
let c = {
  id: 1,
  name: "안수이",
  profile: {
    nickname: "sui",
    urls: ["https://ansui218.tistory.com/"],
  },
};
let { id, name, profile } = c;
let [one, two, three] = [1, "hello", true];

// 함수는 return문 다음에 오는 반환값을 기준으로 추론
function func1() {
  return "hello";
}

// 함수의 매개변수는 기본값으로 추론
function func2(message = "hello") {
  return "hello";
}

 

1️⃣ any 타입의 진화

초기화하지 않으면 암묵적 any 타입으로 추론된다 - 추천 x

// any 타입의 진화
let d;
d = 10; // any -> number로 진화
d; // number 타입

d.toFixed();
d.toUpperCase(); // 오류 발생

d = "hello";
d; // string 타입
d.toUpperCase();
d.toFixed(); // 오류 발생

 

2️⃣ const 이용

: 변하지 않는 상수이므로 리터럴 타입으로 추론된다.

// const 이용
const num = 10; // const num:10 = 10;

// 최적의 공통타입으로 추론
let arr = [1, "string"]; // let arr: (string | number)[]

이정환님의 인프런 강의 "한 입 크기로 잘라 먹는 타입스크립트(TypeScript)"를 참고하여 작성하였습니다.