타입스크립트

김지혜·2023년 8월 4일
0

JS

목록 보기
4/4

⏱ 타입스크립트

⏱ 타입스크립트 실습

💡 프로젝트 세팅

1. 디렉토리 생성 후 명령어 실행

npm init -y
tsc --init --rootDir ./src --outDir ./dist --esModuleInterop --module commonjs --strict true --allowJS true --checkJS true
  • --rootDir ./src
    • 프로그램의 소스 파일이 들어가는 경로는 src 디렉토리
  • --outDir ./dist
    • 컴파일이 된 파일들이 들어가는 디렉토리는 dist 디렉토리
  • --esModuleInterop
    • CommonJS 방식의 모듈을 ES모듈 방식import 구문으로 가져올 수 있다.

2. package.json의 “scripts” 항목을 다음과 같이 변경

"scripts": {
    "start": "tsc && node ./dist/index.js",
    "build": "tsc --build",
    "clean": "tsc --build --clean"
},

3. src 디렉토리도 생성(first_typescript - 프로젝트 디렉토리)

░▒▓ ~/w/first_typescript ▓▒░ ls -al ░▒▓ ✔ │ 08:01:29 PM ▓▒░
total 32
drwxr-xr-x 5 chris staff 160 5 4 20:11 .
drwxr-xr-x 32 chris staff 1024 5 4 18:35 ..
-rw-r--r-- 1 chris staff 230 5 4 19:08 package.json
drwxr-xr-x 3 chris staff 96 5 4 20:11 src
-rw-r--r-- 1 chris staff 11298 5 4 20:10 tsconfig.json

4. 해당 디렉토리 위치를 기반 -> 명령어 실행(Visual Studio Code 편집기)

code .

💡 프로그램 코딩

1. src 디렉토리 안에 index.ts라는 파일을 만든다.

function assignGrade(average: number): string { ... }

2. 함수에 따라 구현하려는 로직 구현

학점을 부여하는 함수

function assignGrade(average: number): string {
  if (average >= 90) {
    return 'A';
  } else if (average >= 80) {
    return 'B';
  } else if (average >= 70) {
    return 'C';
  } else if (average >= 60) {
    return 'D';
  } else {
    return 'F';
  }
}

3. '학생'이 가져야 할 속성들을 정의해서 객체 생성

  • interface는 객체의 구조를 정의하는 방법.
    • 객체가 특정 인터페이스를 구현하려면 인터페이스에 정의된 모든 속성을 가져야 함
interface Student {
  name: string;
  age: number;
  scores: {
    korean: number;
		math: number;
		society: number;
    science: number;
    english: number;
  };
}

4. Student라는 타입의 객체를 받아서 평균을 계산하는 calculateAverage라는 함수를 만들기

function calculateAverage(student: Student): number { ... }

=>

function calculateAverage(student: Student): number {
  const sum = student.scores.korean + student.scores.math + student.scores.society + student.scores.science + student.scores.english;
  // 1. 하드 코딩
  const average = sum / 5;
  return average;
}
  1. -> scores 속성의 개수가 매번 변경된다고 가정을 하면 피곤해짐
    => Object.keys() 함수로 객체 내 특정 속성을 이루는 키 값들을 배열로 반환하기
const average = sum / 5;

=>

const average = sum / Object.keys(student.scores).length;

5. 구하고자 하는 모든 함수 작성 및 코드 작성

6. 실행 시작 (index.ts 파일이 반드시 src 디렉토리 밑에 있는지 확인)

7. 명령어 실행(컴파일)

npm run build

8. 컴파일 완료 후 명령어 실행

npm run start

= 결과


🚨 실행 과정에서 오류 발생

1. npm module 종속성 확인 및 npm 캐시 지우고 다시 설치

npm cache clean --force
rm -rf node_modules
npm install

프로젝트에 TypeScript의 최신 버전이 설치되어 있는지 확인

npm install typescript@latest --save-dev

2. ../tsconfig.json 설정 확인

{
  "compilerOptions": {
    "outDir": "./dist",
    "noImplicitAny": true,
    "module": "ES6",
    "target": "ES5",
    // + "moduleResolution": "node",
    "allowJs": true,
    "sourceMap": true
  }
}

=> moduleResolution이 제대로 입력되었는지 확인
= 실행 시엔 해당 주석 풀기

0개의 댓글