Start TypeScript

sangjuneeeee·2024년 5월 6일

TypeScript

목록 보기
1/9
post-thumbnail

🤷 Why TypeScript?

JavaScript에 있는 문제점을 보완하고 더 나은 개발을 위하여

JavaScript
const input1 = document.getElementById("num1"); const input2 = document.getElementById("num2"); function add(num1, num2) { return num1 + num2; } console.log(add(input1.value, input2.value));
(input) 10, 5 (output) 105

input1.value, input2.value에서 문자열 형태로 받아오기 때문에 실행결과에서 문자열끼리 연결되어 출력됨



문제점 개선

JavaScript
const input1 = document.getElementById("num1"); const input2 = document.getElementById("num2"); function add(num1, num2) { if (typeof num1 === "number" && typeof num2 === "number") { return num1 + num2; } else { return +num1 + num2; } } console.log(add(input1.value, input2.value));
(input) 10, 5 (output) 15

num1, num2가 숫자일 경우 더하거나 명시적으로 숫자로 변경 후 더하도록 함



TypeScript
const input1 = document.getElementById("num1")! as HTMLInputElement; const input2 = document.getElementById("num2")! as HTMLInputElement; function add(num1: number, num2: number) { return num1 + num2; } console.log(add(+input1.value, +input2.value));
(input) 10, 5 (output) 15

형식을 명확하게 하고 형식들을 DoubleCheck하게 하여 오류를 줄일 수 있도록 함




📥 Install TypeScript

Node.js 설치 후

$ npm install -g typescript

컴퓨터 전역에 TypeScript 설치가 됨


📝 How to using TypeScript

$ tsc 파일명.ts

컴파일러가 TypeScript 파일을 JavaScript에 컴파일하여 파일명.js을 생성함

⛔️ zsh: command not found: tsc

$ tsc


zsh: command not found: tsc
$ npm root -g

를 실행시켜 설치 경로를 파악, 본인의 경우 아래의 경로로 명령어 실행 시 해결 됨

$ export PATH="/Users/sangjuneeeee/.npm-global/bin:$PATH"
  • 환경 변수 PATH의 역할: 환경 변수 PATH는 운영 체제에서 실행 파일을 찾는 데 사용되는 경로를 저장하는 변수이다. 터미널에서 명령을 실행할 때, 시스템은 PATH에 정의된 경로를 검색하여 해당 명령을 실행할 수 있는 실행 파일을 찾는다.
  • TypeScript 컴파일러의 경로 추가: export PATH="/Users/sangjuneeeee/.npm-global/bin:$PATH" 명령은 PATH 변수에 /Users/sangjuneeeee/.npm-global/bin 경로를 추가한다. 이 경로에는 전역으로 설치된 TypeScript 컴파일러가 위치한다.
  • 우선순위 설정: PATH 변수에 새로운 경로를 추가하면, 해당 경로의 실행 파일은 기존 경로보다 먼저 검색된다. 따라서 tsc 명령을 실행할 때, 시스템은 먼저 /Users/sangjuneeeee/.npm-global/bin 경로를 검색하여 TypeScript 컴파일러를 찾게 된다.

🚫 터미널 재시작 시 여전히 "zsh: command not found: tsc"가 뜬다면?

.zshrc 파일은 zsh 쉘의 설정 파일로, 터미널을 시작할 때마다 실행된다.

설정이 영구적으로 유지되도록 .zshrc 파일에 추가되었는지 확인해야 한다.

  1. 터미널을 열고 다음 명령어를 실행하여 .zshrc 파일을 연다.
$ nano ~/.zshrc

  1. '.zshrc' 파일의 맨 아래로 이동 후 코드 추가
export PATH="/Users/sangjuneeeee/.npm-global/bin:$PATH"

  1. 추가한 후, Control + X 키를 누르고 Y를 눌러 변경 사항을 저장

  1. 터미널을 재시작하거나 다음 명령어를 실행하여 변경 사항을 적용
source ~/.zshrc



🏃 Easier to Use in Project

프로젝트에서 코드 수정 후 웹 페이지에 빠른 적용을 위함

$ npm init

ㄴ Keep pressing Enter

$ npm install --save-dev lite-server

Add code

"start": "lite-server"

package.json
{ "name": "typescript", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "lite-server" }, "author": "", "license": "ISC", "devDependencies": { "lite-server": "^2.6.1" } }

Execute

$ npm start

참조 : https://ahnheejong.gitbook.io/ts-for-jsdev/

profile
지식 쌓아두기 블로그

0개의 댓글