타입스크립트 설치와 기본 문법

이한재·2023년 1월 24일
0

시작하며

nodejs 를 사용하다보니 vscode 에서 외부 모듈에 대한 함수 정의를 봐야하는 일이 종종 있었고 어떤 모듈은 타입스크립트로 작성이 되어 있어서 타입스크립트에 대한 이해가 조금 필요하다고 느꼈다.

먼저 이글을 작성하는 시점에는 타입스크립트는 자바스크립트를 컴파일해서 사용 할 수 있는 언어라는 정도만 알고 있는 상태이고 타입스크립트에 대해 학습을 해보고 이 글에서 정리를 해보겠다.

TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large applications and transpiles to JavaScript.

TypeScript 를 구글링해봤을때 나오는 wikipedia 에 정리된 내용이다
1. 타입스크립트는 오픈소스 프로그래밍 언어이다
2. 마이크로소프트에서 개발한 언어이다
3. 자바스크립트의 엄격한 문장 superset 이고 옵셔널한 스태틱 타이핑을 언어에 추가했다.
4. large application 을 만들기 위하여 디자인 되었다.

엄격한 문장 superset 이라는건 타입을 지정할 수 있다는 의미 인것 같고 옵셔널 스태틱 타이핑은 옵셔널 값을 지정할 수 있다는 의미인 것 같다.

TypeScript 설치

TypeScript 는 설치 방법이 visual studio 를 통한 설치 또는 npm 으로 설치 할 수 있다고 한다.

npm install -g typescript

test.ts 파일 예시

function sayHello(person: string) {
    return  "Hello, " + person;
}
let user = "Hanjae Lee";
document.body.textContent = sayHello(user);

tsc test.ts 로 컴파일 하면 test.js 파일이 다음과 같이 생성된다

function sayHello(person) {
    return "Hello, " + person;
}
var user = "Hanjae Lee";
document.body.textContent = sayHello(user);

타입스크립트는 함수에 파라미터에 person: string 처럼 타입을 명시해 준다는 것을 확인 할 수 있고

이렇게 컴파일된 test.js 가 웹 브라우저에서 제대로 작동 하는지 확인해 볼 필요성이 있다.

다음과 같이 index.html 을 만들고 브라우저에서 확인해보면

<!DOCTYPE html>
<html>
<head><title>TypeScript sayHello</title></head>
<body>
    <script src="test.js"></script>
</body>
</html>

document.body 에 텍스트가 추가된 것을 확인 할 수 있다.

TypeScript 기본 타입

Boolean

let isLogin : boolean = false;

Number

let num : number = 1;

String

let str : string = 'hello, world';

Object

let obj: object = { name: 'hanjae', age: 31 };

Array

let arr: number[] = [1,2,3];
let arr: Array<number> = [1,2,3];

타입이 배열인 경우 요소의 타입까지 정해주어야 하는데 두가지 방법이 있다.

Tuple

let tuple: [string, number] = ['hanjae', 31]
enum fruits { apple, banana, orange }
let a: fruits = fruits.apple;  
console.log(a) // 0

Any

모든 타입을 저장 할 수 있다

let str: any = 'hi';
let num: any = 10;
let arr: any = ['a', 2, true];

Void

변수에는 undefined 와 null 만 할당가능하고 함수 리턴타입이 void 일 경우에는 return 키워드 사용 불가

function sayHi(): void {
  console.log('hi')
}
  // return 불가
let a: void = null;
let b: void = undefined;

null 타입

let a: null = null;

undefined 타입

let a: undefined = undefined;

Never
never는 일반적으로 함수의 리턴 타입으로 사용되는데, 항상 오류를 출력하거나 리턴 값을 절대로 내보내지 않음을 의미한다.

// 항상 오류 발생
function invalid(message:string): never {
  throw new Error(message);
}
  
// 무한 루프
function infiniteAnimate(): never {
  while ( true ) { infiniteAnimate(); }
}

사용자 정의 타입 (alias)
type 키워드를 사용하여 타입 별칭 (alias) 를 정의 할 수 있다

type operation = {
  data: number[],
  output:(num:number)=>number[]
};
// 사용자 정의 타입 operation 적용 예시
let sum:operation = {
  data: [10, 30, 60],
  output(num){
    return this.data.map(n=>n+num);
  }
};
let multiply:operation = {
  data: [110, 230, 870, 231],
  output(num){
    return this.data.map(n=>n*num);
  }
};

유니온 (Union) 타입

A 이거나 B 이다 라는 의미의 타입으로 두가지 이사으이 타입을 모두 허용하는 경우에 사용한다.
아래 코드에서는 age 는 number 타입이거나 string 타입일 수 있다.

function getAge(age: number | string) : string {
  if (typeof age === 'number') {
    return age.toString();
  }
  else {
    return age;
  }
}
profile
이한재입니다

0개의 댓글