Typescript

김회민·2022년 5월 17일
0

Typescript

목록 보기
1/5

Typescript란?

Javascript + Type

말 그대로 기존의 Javascript에 정적 Type을 명시할 수 있도록 제작된 언어

델파이와 C#의 개발을 주도한 Anders Hejisberg가 개발에 참여하고 있어,
일부 기능이나 문법이 C#과 유사하다.

Type선언 예시

/* Javascript */
const a = 3;
const b = '5';
console.log( a * b ); // 15
/* Typescript */
const a: number = 3;
const b: string = '5';
console.log( a * b ); // compile error!!!

특징

  • JS와 다르게 정적 타입을 명시할 수 있다.
    • 개발 도구에서 개발자가 의도한 변수나 함수 등의 목적을 더욱 명확하게 전달할 수 있다.
    • IDE에서 코드 자동 완성, 잘못된 변수 / 함수 사용에 대한 에러 알림이 가능하다.
  • 브라우저에서 읽을 수 없기 때문에 따로 typescript 컴파일러를 설치하여 js로 변환해주어야 한다.
    • npm install -g typescript
    • tsc <filename>
  • Microsoft에서 만든 언어이기 때문에, 같은 회사에서 만든 vscode와의 궁합이 좋다.
  • C-family 언어이기 때문에 기존의 개발자가 접하면 익숙한 문법이 많이 보인다.
    • Generic : class Stack<T> {}

    • Abstract Class : abstract class Node {}

    • Interface : interface Node {}

    • Decorator

      function firstDecorator( target, name ) {
      	console.log('firstDecorator');
      }
      
      class Person {
      	@firstDecorator
      	job = 'programmer';
      }
      
      const p = new Person();
      console.log( p.job );
      // firstDecorator
      // programmer
  • 어차피 js로 컴파일되어야하기 때문에 JS에서 호환성 문제로 추가되지 못했던 문법을 비교적 자유롭게 채용할 수 있다.
    • Decorator, Abstract Class, Generic, Interface

.d.ts

기존의 JS 코드를 변경하지 않고 typescript로 정의할 수 있게 해주는 파일

/* some-js-library.d.ts */
declare module "some-js-library" {
	function someFunction(a: string, b: string): void;
	class SomeClass {
		/* ... */
	}
}

/* index.ts */
import { someFunction, SomeClass } from "some-js-library";

주의사항

결국에는 JS로 컴파일

런타임에는 약타입

ts-node 를 이용해 디버깅을 할 경우, 클라이언트가 잘못된 type을 넘겨주었을 때 typeerror를 잡아주지만,
실제 운영환경에서는 typescript를 컴파일한 js 파일이 실행이 되므로, 잘못된 type이 넘어와도 검사하지 않는다.

그래서 type guard 함수를 직접 작성하거나, io-ts, runtypes 등의 라이브러리를 사용해 자료형 검사를 따로 실시해주어야 한다.

Any Type의 존재

/* Number Type */
let value: number = 10;
console.log( typeof value ); // number
console.log( value.length ); // compile error!
value = [1, 2, 3, 4];        // compile error!

/* Any Type */
let value2: any = 10;
console.log( typeof value2 ); // number
console.log( value2.length ); // undefined. but running
value2 = [1, 2, 3, 4];        // ok
console.log( typeof value2 ); // object
console.log( value2.length ); // 4

/* Unknown Type */
let value3: unknown = 10;
console.log( typeof value3 ); // number
console.log( value3.length ); // compile error!
value3 = [1, 2, 3, 4];        // ok
console.log( typeof value3 ); // object
console.log( value3.length ); // 4

Any Type

  • 모든 타입을 허용한다.
  • 해당 타입에 없는 property를 호출해도 undefined가 뜰 뿐, 프로그램이 종료가 되지 않는다.

Unknown Type

  • 모든 타입을 허용한다.
  • 해당 타입에 없는 property를 호출하면 complie error가 뜬다.
profile
백엔드 개발자 지망생

0개의 댓글