TypeScript의 기본 (Structural Type System)

White Piano·2020년 10월 26일
2

TypeScript Handbook

목록 보기
1/3

TypeScript for JavaScript Programmers의 일부를 요약 및 정리한 글입니다.

Types by Inference

변수의 선언과 동시에 값을 할당하면, Type이 묵시적으로 결정됩니다.

// 아래의 두 Statement는 동일합니다.
let helloWorld = "Hello World";
let helloWorld: string = "Hello World";

Interface

// User Interface 정의
interface User {
  name: string;
  id: number;
};

// Usages
const user1: User = {
  name: "Steve",
  id: 0,
};
const user2: User = new UserClass('Steve', 0);
function convertUser(user: User): User {
  ...
};

Unions

여러 Type을 합쳐서 더 복잡한 Type을 정의할 수 있습니다.

// WindowStates Type은 'open', 'closed', 'minimaized' 중 하나의 값을 가집니다.
type WindowStates = 'open' | 'closed' | 'minimaized';

let window1: WindowStates = 'open';  // OK
let window2: WindowStates = 'state'; // error

Generics

자료형을 변수(?)처럼 지정할 수 있습니다.

// Backpack Interface 정의
interface Backpack<Type> {
  add: (item: Type) => void;
  get: () => Type;
};

// bp 상수(const)가 어딘가 정의되어 있음을 의미합니다.
declare const bp: Backpack<string>;

// bp이 Backpack<string> Type라는 것을 알고 있습니다.
const str: string = bp.get(); // OK
const num: number = bp.get(); // error

Structural Type System

"Duck Typing", "Structural Typing"이라고도 불립니다.

서로 다른 Type이더라도, 필요한 property만 존재하면 됩니다. property의 순서가 달라도, 추가로 다른 property가 있더라도 문제없습니다!

interface foo {
  name: string,
};

let bar = {
  name: 'hello',
  age: 10,
};

let f: foo = b; // OK

주의! Object LiteralExcess Property Check를 진행합니다. 자세한 내용은 여기를 참고해 주세요!

0개의 댓글