npm init -y : package.json 초기화
npm install -D typescript : -D 는 --save-dev와 동일
npx tsc --version : 버전확인
npx tsc --init : typescript의 컴파일 과정 옵션을 설정할 수 있는 파일인 tsconfig.json 생성 명령어
// javascript
const num = 20;
const str ="javascript"
const nan = NaN;
const infinity = Infinity;
const bool = true;
const nullvalue = null;
const undefinedValue = undefined;
const obj ={};
const arr =[];
const fn = (a)=>{
console.log(a);
}
const sum = (a , b) =>{
return a + b;
}
const any ="";
const unknown = "";
// typescript
const num2 : number = 20;
const str2 : string = "typescript"
const nan2 : number = NaN;
const infinity2 : number = Infinity;
const bool2 : boolean = true;
const nullvalue2 : null = null;
const undefinedValue2 : undefined = undefined;
const obj2 : object ={};
// <>: 제네릭 타입으로 배열의 요소를 설정가능 아래 코드는 string, number 둘다 가능
const arr2 : Array<number | string> = ['s',1];
// 타입 추론 없이 배열 선언
const strArr : string[] = ["1","2","3"];
const numArr : number[] = [1,2,3];
// 튜플
// 각 배열의 자리에 타입을 지정
const tuple : [string,number,object] = ["hello",123,{}];
// void : 함수 실행시 비어있다는 것을 의미, 반환값이 없는 함수라는 것
const fn2 =(a:number):void=>{
console.log(a);
}
// 함수명 = () : return의 타입지정 =>{}
const sum2 =(a:number, b:number):number =>{
return a+b;
}
// any : 어떤 타입이든 할당할 수 있다.
// 타입의 안정성 보장되지 않아 남발하지 말자.
const any2 : any = ""
console.log(any2.length);
// unknown : 어떤 타입이든 할당 가능 타입의 안정성 보장
const unknown2 : unknown = "";
if(typeof unknown2 === "string")
// 아래 콘솔만 적으면 당연히 오류가 난다. 하지만 if문을 통하면 오류가 안남.
console.log(unknown2.length)
ts-node는 javascript 파일을 만들지않고, 내부 컴파일러를 통해 메모리 상에 javascript 코드로 변환하고, 그 코드를 node js 런타임 환경으로 실행하여 결과를 출력한다.
tsconfig.json란 ?
typescript의 컴파일 과정 옵션을 설정할 수 있는 파일이다.
파일안에는 compilerOptions , include, exclude 파일의 동작을 설정할 수 있는 키가 있다.
compilerOptions : typescript 파일을 컴파일 시 어떤 형태로 컴파일을 진행할지 정의
include : 컴파일을 진행할 폴더를 지정
exclude : 컴파일에서 제외할 폴더를 지정
위 사진처럼 설정을 하고, package.json의 scripts 에 "build":"tsc"을 추가하고,
npm run build 를 하면 dist 폴더가 생성이 되면서
컴파일 되는데, exclude로 제외한 message.test.ts 파일은 컴파일 되지 않은걸 볼 수 있다.
하지만, 이것도 완벽하게 컴파일 된것이 아니다. 그 이유는
message.ts에서
import a from "@user/server/user.service"
별칭으로 import 하여 가져온 파일이 컴파일 된 파일인
message.js에서
const user_service_1 = __importDefault(require("@user/server/user.service"));
별칭으로 그대로 남아있기 때문에 javascript 에서는 인식하지 못하기 때문이다.
그래서, 이 별칭을 경로로 변환해주는 패키지인
tsc-alias 를 이용해 변환해줘야한다.
npm install -D tsc-alias 로 설치 후,
package.json의 scripts 영역에
{
"build" : "tsc && tsc-alias",
}
위와 같이 추가하면 경로까지 바뀌고,
완벽한 컴파일이 된다.