본문 바로가기
프론트엔드/TypeScript

리터럴, 유니온/교차 타입

by alswlfl 2023. 1. 3.

리터럴 타입(Literal Types)

  • const: 변하지 않는 값 선언 할 때
  • let: 변할 수 있는 값 선언 할 때
  • 문자열 리터럴 타입: 정해진 string 값을 가진 값
const userName1="Bob"; //문자열 리터럴 타입: 정해진 string값을 가진 값
let userName2="Tom"; 
let userName3:string | number="Tom";  //가질 수 있는 타입 명시 하기

type Job="police"|"developer" |"teacher";

interface User{
  name:string;
  job:Job;
}

const user: User = {
  name:"Bob",
  job:"developer",
};

유니온 타입(Union Types)

  • |(세로 줄)
interface HighSchoolStudent{
  name: number | string;
  grade: 1|2|3;
}
// Union types
interface Car{
  name:"car";
  color: string;
  start():void;
}

interface Mobile{
  name: "mobile";
  color: string;
  call():void;
}

function getGift(gift:Car | Mobile){
  console.log(gift.color);
  if(gift.name==="car"){. //car인지 확인 한 후, 해당 메서드 출력
    gift.start();
  }else{
    gift.call();
  }
}

교차 타입(Intersection Types)

  • 여러 개의 타입을 하나로 합쳐주는 역할
  • 필요한 기능을 모두 가진 하나의 타입이 만들어짐
// Intersection Types
interface Car{
  name: string;
  start():void;
}

interface Toy{
  name: string;
  color: string;
  price: number;
}

const toyCar: Toy & Car = {
  name:"타요",
  start(){},
  color: "blue",
  price: 1000,
}

'프론트엔드 > TypeScript' 카테고리의 다른 글

제네릭  (0) 2023.01.03
클래스  (0) 2023.01.03
함수  (0) 2023.01.03
인터페이스  (0) 2023.01.03
TypeScript 사용 이유와 기본 타입  (0) 2023.01.03