npm init -y
// package.json 파일 만들기
npm install typescript --save-dev
// typescript 설치
tsconfig.json 파일 만들기 (어떻게 JS로 변환하는지 설정할 예정)
index.ts 파일 만들고 console.log('hello') 작성하기
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs", // node.js를 평범하게 사용하고 import, export 할 수 있음
"target": "ES2016", // 어떤 버전의 JS로 컴파일 하고 싶은지
"sourceMap":true // sourcemap 처리를 하고싶은지
},
"include": ["index.ts"], // 컴파일 과정에서 포함할 파일의 배열
"exclude": ["node_modules"]
}
npx tsc
하면 컴파일됨. index.js, index.js.map 파일 생성됨.
( 글로벌로 typescript 를 설치했다면 tsc 명령어만으로 충분)
// package.json
"scripts": {
"start": "node index.js",
"prestart": "npx tsc"
},
이렇게 설정해두고 npm start
하면 prestart -> start 순으로 실행된다.
Node.js 는 Typescript 를 이해하지 못해서 Javascript 코드로 컴파일하는 작업 필요
특정 파라미터뒤에 ?
를 사용하면 선택적인 파라미터라는 뜻이다.
const name = "Nicolas",
age = 24,
gender = "male";
const sayHi = (name, age, gender?) => { // gender 로 하면
console.log(`Hello ${name}, you are ${age}, you are a ${gender}`);
};
sayHi(name, age); // 이 부분에서 인자 3개 받으라고 에러뜸
export {};
빈 값이라는 뜻
// 리턴하는 값이 없으니까 void 로 할 수 있음
const sayHi = (name, age, gender): void => {
console.log(`Hello ${name}, you are ${age}, you are a {gender}`);
};
// 리턴하는 값이 있으면 void로 하는 경우 에러가 뜸
const sayHi = (name, age, gender): string => {
return `Hello ${name}, you are ${age}, you are a ${gender}`;
};
수정할 때마다 npm start 하면 귀찮으니까. 자동으로 설정해보기 (nodemon 과 비슷)
npm install tsc-watch --save-dev
// tsc-watch 설치
package.json 파일 scripts 부분 에서 prestart 지우고
"start": "npx tsc-watch --onSuccess \" node dist/index.js\" "
로 수정
src, dist 폴더 각각 생성
index.ts 파일 src 폴더로 안으로 이동
.gitignore 에 dist 추가
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2016",
"sourceMap": true,
"outDir": "dist" // 컴파일 된 모든 건 dist 폴더로 들어감
},
"include": ["src/**/*"], // 내 모든 ts는 src 폴더로 들어감
"exclude": ["node_modules"]
}
npm start
하면 터미널에서 watch 모드에서 컴파일 시작함
(수정하고 저장할 때마다 콘솔 내용 실시간 출력함)
dist 폴더 보면 index.js, index.js.map 파일 있음
ts 에서만 작동함. js 에서는 작동되지 않음. 컴파일도 되지 않음
interface Human { // 나만의 object
name: string;
age: number;
gender: string;
};
const person = {
name: "nicolas",
age: 22,
gender: "male"
};
const sayHi = (person:Human): string => {
return `Hello ${person.name}, you are ${person.age},
you are a ${person.gender}!`;
}; // person. 하는 순간 VSC가 코딩을 도와준다는 것을 느낄 수 있음(ts장점)
console.log(sayHi(person));
export {};
interface 를 굳이 js 에서 쓰고싶다면 (아마 써야하는 상황이 있을 수 있음)
class 활용하기
class Human {
public name: string; // public 하면 바깥에서 부를 수 있음
public age: number; // js 에서는 없음
public gender: string; // private 하면 바깥에서 호출할 때 에러뜸
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const lynn = new Human("Lynn", 18, "female")
const sayHi = (person:Human): string => {
return `Hello ${person.name}, you are ${person.age},
you are a ${person.gender}!`;
};
console.log(sayHi(lynn));
export {};
index.js 보면 class 부분 컴파일 확인가능
public, private 관련해 컴파일 된 부분은 없음(js는 신경안쓰니까)