undefined
. Do not use null
.쉽게 시작하는 타입스크립트 (https://joshua1988.github.io/ts/intro.html)
Interface
interface 인터페이스_이름 {
속성?: 타입;
}
Union Type, Enum, Intersection Type
Union Type
type Color = "Red" | "Black" | "White";
console.log(Color); // error
열거형(enum)
enum Color {
Red,
Green,
Blue,
}
console.log(Color); // no error
Intersection Type
interface Person {
name: string;
age: number;
}
interface Developer {
name: string;
skill: number;
}
type Capt = Person & Developer; // { name: string; age: number; skill: string; }
제네릭(Generics)
function logText<T>(text: T): T {
return text;
}
타입추론
타입호환
타입별칭
type
보다는 interface
로 선언하여 사용하는 것 권장타입단언
as
키워드 사용Usage
https://joshua1988.github.io/ts/usage/modules.html => ING
https://www.typescriptlang.org/docs/handbook/intro.html
tsconfig 파일 분리
compilerOptions.moduleResolution
TypeScript 컴파일러가 모듈을 해석하는 방법을 설정하는 옵션
이 옵션은 주로 모듈을 찾는 방식과 관련하여 사용됨
tsconfig.json
{
"compilerOptions": {
// 기본 설정
"target": "ES2020", // 타입스크립트가 최종적으로 변환하는 JavaScript 버전.
"useDefineForClassFields": true, // 클래스 필드를 define 방식(Object.defineProperty)으로 정의. 클래스 필드 초기화가 표준 JS 동작과 일치하게 됨.
"lib": ["ES2020", "DOM", "DOM.Iterable"], // 타입스크립트가 빌드할 때 참고할 JS 표준 API 목록.
"types": [], // 기본 타입 선언 파일(ex: @types/node)을 비활성화.
// 모듈 설정 (Bundler용)
"module": "ESNext", // import/export를 변환하지 않고 그대로 남김. 번들러(예: Vite, Webpack)가 나중에 처리하게 함.
"moduleResolution": "bundler", // Bundler 스타일로 모듈 경로를 해석. vite, rollup, webpack에 최적화된 경로 처리.
"allowImportingTsExtensions": true, // .ts, .tsx 확장자를 가진 파일을 import할 때 확장자까지 명시할 수 있도록 허용.
"resolveJsonModule": true, // JSON 파일을 import할 수 있게 해줌.
"isolatedModules": true, // 각 파일을 독립된 모듈처럼 검사. 단일 파일만 빌드할 수 있도록 강제 (Babel 같은 툴과 호환성 높임).
"jsx": "react-jsx", // **React 17+**의 새로운 JSX 변환 방식을 사용 (import React from 'react' 안 해도 됨).
/* Linting */
"strict": true,
"noUnusedLocals": true, // 사용하지 않는 지역 변수 있으면 에러.
"noUnusedParameters": true, // 사용하지 않는 함수 매개변수 있으면 에러.
"noFallthroughCasesInSwitch": true // switch문에서 case마다 break 안 하면 에러.
"skipLibCheck": true, // 빌드 속도 빨라짐, 외부 라이브러리 오류로 인한 빌드 실패 방지
},
}
tsconfig.types.json
예시tsc -p tsconfig.types.json
{
"extends": "./tsconfig.json", // 기본 설정 가져옴
"compilerOptions": {
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "lib",
"skipLibCheck": true,
"stripInternal": true,
"composite": true,
"declarationMap": true,
"preserveSymlinks": true
},
"include": [
"src/**/*"
],
"exclude": [
"src/**/*.test.ts",
"src/**/*.test.tsx",
"src/**/*.spec.ts",
"src/**/*.spec.tsx",
"src/**/__tests__/**",
"node_modules",
"dist",
"lib"
]
}