Typescript 문법 정리

김재환·2023년 12월 28일

TypeScript

목록 보기
6/7

리터럴 타입

특정한 숫자나 문자열 같이 변수의 값을 타입으로 하는 타입입니다. 각 리터럴 타입들은 string이나 number 같은 더 큰 타입에 포함됩니다.


const name = 'codeit'; // 'codeit' 이라는 리터럴 타입
const rank = 1; // 1 이라는 리터럴 타입

타입 별칭

복잡한 타입에 이름을 붙이고 재사용하고 싶을 때 사용합니다.

type Point = [number, number];
type SearchQuery = string | string[];
type Result = SuccessResult | FailedResult;
type Coupon = 
  | PromotionCoupon
  | EmployeeCoupon
  | WelcomCoupon
  | RewardCoupon
  ;   

Union

A이거나 또는 B인 경우를 타입으로 만들고 싶을 때

ClothingProduct | ShoeProduct

Intersection

A와 B의 성질을 모두 갖는 타입을 만들고 싶을 때

interface Entity {
  id: string;
  createdAt: Date;
  updatedAt: Date;
}

type Product = Entity & {
  name: string;
  price: number;
  membersOnly?: boolean;
}

하지만 보통 이럴 때는 interface와 상속을 사용하시는 걸 권장드립니다.

interface Entity {
  id: string;
  createdAt: Date;
  updatedAt: Date;
}

interface Product extends Entity {
  name: string;
  price: number;
  membersOnly?: boolean;
}

keyof 연산자

객체 타입에서 프로퍼티 이름들을 모아서 Union한 타입으로 만들고 싶을 때 사용합니다.

interface Product {
  id: string;
  name: string;
  price: number;
  membersOnly?: boolean;
}

type ProductProperty = keyof Product; // 'id' | 'name' | 'price' | 'membersOnly';

typeof 연산자

자바스크립트 코드에서 사용하면 결괏값이 문자열이지만, 타입스크립트 코드에서 쓸 때는 결과 값은 타입스크립트의 타입입니다.

const product: Product = {
  id: 'c001',
  name: '코드잇 블랙 후드 집업',
  price: 129000,
  salePrice: 98000,
  membersOnly: true,
};

console.log(typeof product); // 문자열 'object'

const product2: typeof product = { // 타입스크립트의 Product 타입
  id: 'g001',
  name: '코드잇 텀블러',
  price: 25000,
  salePrice: 19000,
  membersOnly: false,
};
profile
안녕하세요

0개의 댓글