본문 바로가기

FrontEnd/Typescript

[노드교과서] 타입스크립트

타입스크립트는 자바 스크립트에 명시적으로 타입이 추가된 언어이다.

타입으로 인하여 자유도를 포기하지만 미리 안정성을 챙기는 언어이다.

 

디노(deno)라는 타입스크립트를 실행할 수 있는 런타임이 있긴 하지만 아직은 대중적이지 않다.

그러므로 타입 스크립트 코드는 tsc라는 컴파일러를 통해 자바스크립트로 변환해 노드와 함께 사용하고 있다.

$ npm i typescript  // tsc를 설치(타입스크립트 컴파일러)

// 현재 프로젝트를 typescript project로 변경
// tsconfig.json 생성
$ npx tsc --init

 

 tsc는 type검사와 javascript변환을 담당하나 typescript에서 type오류가 발생 했더라도 javascript변환을 막진 않는다.

type의 경우 javascript에서는 문제가 발생하지 않기 때문이다.

오류에 대한 검사만 하고 싶을 때는 npx tsc --noEmit를 입력하라.

 

 

 

 

// index.ts
let a = 'hello'
a = 'world'

$ npx tsc

// indes.js
"use strict";
let a = 'hello';
a = 'world';

 

분류 설명 예시
기본형 string, number, boolean,symbol
, object, undefined, null, bigint
const a: string = 'hello';
const b: object = { hello : 'ts' };
배열 타입 뒤에 []을 붙인다.길이가 고정된
배열(튜플이라함)이면 [] 안에 타입을 적는다.

const a: string[] = ['hello', 'ts', 'js'];

const b: [number, string] = [123, 'node'];
상수 1, 'hello', true 등의 고정 값 const a: 1 = 1;
변수 typeof 변수로 해당 변수의 타입 사용 가능 let a = 'hello';
const b: typeof a = 'ts';
클래스 클래스 이름을 그대로 인스턴스의
타입으로 사용이 가능하다.
class A {}
const a = new A();
type 선언 다른 타입들을 조합해서 새로운 타입 생성가능.
유니언(|), 인터섹션(&) 사용 가능
const a: { hello : string } = { hello : 'ts' };
type B = { wow : number };
const b: B = { wow : 123 };
type C = string | number;
let c: C = 123;
c = '123';
인터페이스 객체에 대한 type을 인터페이스로도 선언가능.
또한 클래스 인스턴스나 함수도 선언이 가능하다.
interface A { hello : string, wow: number }
const a: A = { hello : 'ts', wow : 123};