npm install -g typescript
ํด๋น ํ๋ก์ ํธ๋ก ์ด๋ํ์ฌ ์งํ
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 ๊ตฌ๋ฌธ์ผ๋ก ๊ฐ์ ธ์ฌ ์ ์์.
"scripts": {
"start": "tsc && node ./dist/index.js",
"build": "tsc --build",
"clean": "tsc --build --clean"
},
interface Student {
name: string;
age: number;
scores: {
korean: number;
math: number;
society: number;
science: number;
english: number;
};
}
function createStudent(name: string, age: number, korean: number, math: number, society: number, science: number, english: number): Student {
return {
name,
age,
scores: {
korean,
math,
society,
science,
english,
},
};
}
function calculateAverage(student: Student): number {
const sum = student.scores.korean + student.scores.math + student.scores.society + student.scores.science + student.scores.english;
const average = sum / 5;
return average;
}
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';
}
}
function printResult(student: Student): void {
const average = calculateAverage(student);
const grade = assignGrade(average);
console.log(`${student.name} (${student.age}์ธ) - ํ๊ท : ${average.toFixed(2)}, ํ์ : ${grade}`);
}
function main(): void {
const spartan = createStudent('Spartan', 30, 95, 89, 76, 90, 97);
printResult(spartan);
}
main();
๋ก์ง ์ถ๊ฐ
์ปดํ์ผ ์๋ฌ๊ฐ ์์ผ๋ฉด ์ด๋ ์๋ฌ๊ฐ ๋ฐ์ํจ.
ts -> js ๋ฐ๊ฟ์ฃผ๋๋ฏ
npm run build
dist ํด๋๋ ๋ญ๊น?
- distribution์ ์ฝ์
- src์ typescript ์ฝ๋๊ฐ nodejs์์ ์๋ํ๊ธฐ ์ํด javascript ์ฝ๋๋ก ์ปดํ์ผ๋ ๊ฒฐ๊ณผ๋ฌผ.
npm run start
์ฐธ๊ณ :
https://myung-ho.tistory.com/94
https://inpa.tistory.com/entry/TS-%F0%9F%93%98-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-tsconfigjson-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0-%EC%B4%9D%EC%A0%95%EB%A6%AC