박서희연구소

[TypeScript] TypeScript 는 왜 사용하는가? 본문

○ Programming [Basic]/TypeScript

[TypeScript] TypeScript 는 왜 사용하는가?

SEOHUI PARK 2022. 12. 12. 14:30
반응형

1. TypeScript 란?

TypeScript 는 JavaScript 의 모든 기능과 Type System 이라는 추가적인 계층을 제공한다.

예를 들면, JavaScript 는 stringnumber 같은 Primitive Type 을 제공하나 이를 맞게 할당했는지 확인하지 않는다. 그러나 TypeScript 는 이를 확인한다.

이런 장점으로 인해 버그 발생의 확률을 낮출 수 있다.

 

2. 추론에 의한 Type

TypeScript 는 JavaScript 언어를 알고 있으며, 변수를 생성하고 값을 할당할 때, Type 을 사용한다.

 

3. Type 정의

JavaScript 에서 넓고 다양한 디자인 패턴을 사용할 수 있지만, 일부 디자인 패턴은 Type 을 자동으로 추론하기 어렵다.

이런 케이스 때문에 TypeScript 는 Type 이 무엇인지 알려줄 수 있는 JavaScript 의 확장된 기능을 제공한다.

interface 를 선언해, Object 의 형태로 사용할 수 있다.

변수 선언 뒤에 : TypeName 같은 구문을 사용해 새로운 interface 의 형태로 JavaScript Object 를 선언할 수 있다.

interface Student {
  name: string;
  id: number;
}

JavaScript 는 object-oriented programming(OOP) 을 지원하기 때문에, TypeScript 또한 이를 지원한다.

class 와 함께 interface 도 선언할 수 있다.

interface Student {
  name: string;
  id: number;
}
 
class StudentAccount {
  name: string;
  id: number;
 
  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}
 
const student: StudentAccount = new StudentAccount("Seohui", 1);

interface 를 사용하여 파라미터에 어노테이션을 주고, 함수의 값을 반환할 수 있다.

function getStudent(): Student {

}
 
function deleteStudent(student: Student) {

}

 

4. Type 조립

TypeScript 의 사용으로 간단한 Type 을 결합해, 복잡한 Type 을 생성할 수 있다.

unionsgenerics 를 사용하는 두 가지의 대표적인 방법이 있다.

 

[Unions]

boolean 의 값으로 true 또는 false 가 있다.

이런 Type 은 이런 형태로 생성할 수 있다.

type SeohuiBool = true | false;

주로 stringnumber 를 사용한 집합을 선언하는 형태가 자주 사용된다.

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

다양한 형식을 처리하는 방법도 제공한다.

function getLength(obj: string | string[]) {
  return obj.length;
}

변수의 Type 을 알아보기 위해서는 typeof 를 사용하면 된다.

예로 문자열 또는 배열을 전달했는지 여부에 따라 다른 값을 반환하는 함수를 만들어 볼 수 있다.

function wrapInArray(obj: string | string[]) {
  if (typeof obj === "string") {
    return [obj];
  }
  return obj;
}

[Generics]

Generics 는 Type 에 변수를 제공한다.

Array 로 예를 들면, Generics 가 없는 Array 는 어떤 것이든 포함할 수 있다.

Generics 와 함께하는 Array 는 배열에 포함된 값을 describe 할 수 있다.

interface Fruit<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}

declare const fruit: Fruit<string>;
 
const object = fruit.get();
 
fruit.add(23); // string 형태의 인자만 사용 가능하므로 오류

[Structural Type System]

TypeScript 의 중요한 원칙 중 하나는 값의 형태의 초점을 맞춘 Type 체크이다.

이를 "duck typing" 또는 "strctural typing" 이라고 부른다.

structural type system 에서 두 객체의 형태가 같으면 동일한 Type 으로 간주된다.

interface Point {
  x: number;
  y: number;
}
 
function logPoint(p: Point) {
  console.log(`${p.x}, ${p.y}`);
}
 
const point = { x: 12, y: 26 };
logPoint(point);

const point3 = { x: 12, y: 26, z: 89 };
logPoint(point3); // logs "12, 26"
 
const rect = { x: 33, y: 3, width: 30, height: 80 };
logPoint(rect); // logs "33, 3"
 
const color = { hex: "#187ABF" };
logPoint(color); // 이 케이스는 실패

point 변수는 Point Type 으로 선언되지 않았다.

그러나 TypeScript 는 type-check 에서 point 의 형태와 Point 의 형태를 비교하며, 같은 형태를 하므로 이는 실패한 코드가 아닌 통과하는 코드가 된다.

개체 필드의 subset 만 일치하면, 이는 shape-matching 으로 간주한다.

 

- 끝 -

반응형
Comments