저장을 습관화
타입스크립트 입문 기록 본문
작업 환경: Windows 10, VSC
목표:
TypeScript 프로젝트에서 JavaScript 라이브러리를 임포트(사용)할 수 있게 해주는 d.ts 파일 실습
작업 기록
1. 타입스크립트 설치와 tsconfig.json 설정
$ npm init -y
$ npm install -g typescript
// -g는 global의 약자, 패키지를 전역설치하여
// 컴퓨터의 모든 프로젝트에서 사용할 수 있게 한다
// 타입스크립트는 괜찮지만 패키지의 버전이
// 모든 프로젝트와 호환될거라는 보장은 없으니
// 주의해서 사용해야 한다.
$ tsc --init
// tsconfig.json 파일 생성 확인
2. tsconfig.json에서 allowJs, checkJs의 주석을 해제한다.
allowJs는 TypeScript 프로젝트에 JavaScript 파일 허용 여부를 설정하는 것이고,
checkJs는 JavaScript 파일 타입 테크 여부를 설정하는 것이다.
3. 직접 만든 자바스크립트 라이브러리가 타입스크립트에서 사용이 되는가를 확인한다.
// TypeScript에서 사용하고 싶은 커스텀 JavaScript 라이브러리를 만든다.
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
export function add(a, b) {
return a + b;
}
주석의 내용은 '매개변수 a, b 그리고 return의 데이터타입은 number로 하겠다'를 JSDoc으로 표현한 것이다.
4. d.ts 파일을 생성한다.
$ npx tsc test.js --declaration --allowJs --emitDeclarationOnly --outDir types
터니널에서 명령어를 입력하면 /types 폴더와 그 아래 test.d.ts 파일이 생성된 것을 확인할 수 있다.
test.d.ts 파일의 내용은 다음과 같다.
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
export function add(a: number, b: number): number;
test.js에서 선언했던 것과 같이 함수 add를 선언하면서 매개변수 a, b 그리고 return은 number라고 명시하였다.
5. 확인
foo.ts 파일을 만든다.
import { add } from "./test";
console.log(add(1, 2));
터미널에서 실행시켜보면
$ npx ts-node foo.ts
만약 전달인자가 number 아니면 코드 창에서 에러 표시가 나오고
이 상황에서 실행시키면 아래와 같은 에러 로그가 출력된다.
number 타입 parameter에 string 타입 argument를 할당할 수 없다라는 의미다.
$ npx ts-node foo.ts
C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:859
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
^
TSError: ⨯ Unable to compile TypeScript:
foo.ts:2:20 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
2 console.log(add(1, "2"));
~~~
at createTSError (C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:859:12)
at reportTSError (C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:863:19)
at getOutput (C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:1077:36)
at Object.compile (C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:1433:41)
at Module.m._compile (C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:1617:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Object.require.extensions.<computed> [as .ts] (C:\Users\admin\AppData\Local\npm-cache\_npx\1bf7c3c15bf47d04\node_modules\ts-node\src\index.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Function.Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
diagnosticCodes: [ 2345 ]
}
'공부 > TypeScript' 카테고리의 다른 글
타입스크립트에서 자주 쓰이는 유틸리티 타입 (0) | 2023.07.29 |
---|---|
타입스크립트에서의 데이터 타입 사용 방법 2 - any, unknown, union, object literal (0) | 2023.07.29 |
타입스크립트에서의 변수, 상수 선언 - let, const, readonly (0) | 2023.07.29 |
타입스크립트에서의 데이터 타입 사용 방법 - boolean, number, string, array, tuple, enum (0) | 2023.07.28 |
TypeScript 연습 - 성적표 프로그램 만들기 (0) | 2023.07.28 |