TypeScript 사용법

https://www.typescriptlang.org/
https://github.com/microsoft/TypeScript


* 설치
npm install typescript --save-dev


---------------------------------------
* package.json 파일 예제
{
    "private": true,
    "type": "module",
    "scripts": {
        "build:ts": "tsc",
        "watch:ts": "tsc --watch",

}
}


---------------------------------------
* tsconfig.json 파일 예제
{
    "compilerOptions": {
        "target": "es2022", // 컴파일 결과물
        "module": "es2022", // 변환할 모듈 시스템
        "moduleResolution": "bundler", // 모듈 해석 방식
        "strict": true, // 엄격한 타입 체킹 활성화
        "esModuleInterop": true, // CommonJS 모듈과 ES Module 간의 호환성을 추가로 보장
        "skipLibCheck": true, // 타입 선언 파일(d.ts)에 대한 타입 검사를 생략
        //"forceConsistentCasingInFileNames": true, // 파일명 대소문자 일관성을 강제
        //"jsx": "preserve", // JSX 문법이 JS로 변환되는 방식을 지정, React/Vue 사용 시 필요
        //"noEmit": true, // 컴파일 결과 파일(js, map, d.ts 등)을 생성하지 않음
        "isolatedModules": true, // 각 파일을 개별 모듈로 분리해서 타입체크
        "rootDir": "./resources/ts", // TypeScript 소스 파일이 있는 루트 디렉토리
        "outDir": "./public/js/dev1/esm", // 컴파일된 JavaScript 파일이 저장될 디렉토리
        "sourceMap": true // 디버깅을 위한 소스맵 파일 생성 여부
    },
    "include": [
        "resources/ts/**/*.ts", // 타입스크립트 파일 경로
        "resources/ts/types/**/*.d.ts" // 타입 선언(Type Declaration) 파일
    ],
    "exclude": [ "node_modules", "storage", "vendor", "z", "bak", "test", "app", ".*" ]
}


---------------------------------------
* ts 파일 변경 감지해서 자동 컴파일

npm run watch:ts


---------------------------------------
*  타입 선언(Type Declaration) 파일 - *.d.ts 파일
- JavaScript로 작성된 코드의 타입정보
- 로직은 없고 선언만 있음
- 컴파일 할때 참조됨


- tsconfig.json의 include 설정하면 자동으로 사용(import 과정 필요 없음)
- 예제
"include": [
    "src/**/*.ts", // src 폴더의 모든 .ts 파일을 포함
    "src/types/**/*.d.ts" // src/types 폴더의 모든 .d.ts 파일을 포함
  ]

- utils.d.ts 파일 예제
export function createUserId(name: string, id: number): string;

export const DEFAULT_TIMEOUT: number;

반응형
Posted by codens