TypeScript의 타입 체크 옵션은 코드의 안정성을 결정합니다. Sonamu는 strict 모드를 기본으로 활성화하여 최대한의 타입 안정성을 제공합니다.
Strict 모드
Sonamu는 모든 strict 옵션을 활성화합니다.
{ "compilerOptions": { "strict": true, // 모든 strict 옵션 활성화 "noImplicitAny": true, // any 타입 명시 필요 "strictNullChecks": true, // null/undefined 엄격 체크 "strictFunctionTypes": true, // 함수 타입 엄격 체크 "strictBindCallApply": true, // bind/call/apply 엄격 체크 "strictPropertyInitialization": true, // 클래스 프로퍼티 초기화 필요 "noImplicitThis": true, // this 타입 명시 필요 "alwaysStrict": true // 'use strict' 자동 추가 }}
strict: true는 위의 모든 옵션을 한 번에 활성화하는 단축 설정입니다.
Strict 옵션 상세
noImplicitAny
strictNullChecks
strictFunctionTypes
strictBindCallApply
strictPropertyInitialization
noImplicitThis
any 타입 명시 필요
기능:
타입을 추론할 수 없을 때 any를 암묵적으로 사용하지 못하도록 방지
예시:
// ❌ 에러 발생function log(message) { // ^^^^^^^ Parameter 'message' implicitly has an 'any' type console.log(message);}// ✅ 올바른 코드function log(message: string) { console.log(message);}// ✅ 제네릭 사용function log<T>(message: T) { console.log(message);}
타입을 명시하기 어려운 경우 unknown을 사용하세요. any보다 안전합니다.
null/undefined 엄격 체크
기능:
null과 undefined를 다른 타입에 할당할 수 없도록 방지
모든 타입이 기본적으로 non-nullable
예시:
// ❌ 에러 발생let name: string = null;// ^^^^ Type 'null' is not assignable to type 'string'// ✅ Union 타입 사용let name: string | null = null;name = "Alice";// ✅ Optional 체이닝interface User { email?: string;}function sendEmail(user: User) { // ❌ 에러 발생 const length = user.email.length; // ^^^^^ Object is possibly 'undefined' // ✅ Optional 체이닝 const length = user.email?.length; // ✅ null 체크 if (user.email !== undefined) { const length = user.email.length; }}
Sonamu에서:
// entity.json으로 정의된 Entity 사용interface User { id: number; name: string; // null이 될 수 없음 bio: string | null; // null 허용 email?: string; // undefined 허용 created_at: Date;}// Model 클래스에서 타입 안정성 확보class UserModelClass extends BaseModelClass { @api({ httpMethod: "GET" }) async findById( subset: UserSubsetKey, id: number ): Promise<UserSubsetMapping[typeof subset] | null> { const rdb = this.getPuri("r"); const user = await rdb.table("users").where("id", id).first(); // strictNullChecks가 null 체크를 강제함 if (!user) { return null; } return user; }}
함수 타입 엄격 체크
기능:
함수 파라미터의 contravariance(반공변성) 체크
더 안전한 함수 타입 호환성
예시:
interface Animal { name: string;}interface Dog extends Animal { bark(): void;}// ❌ 에러 발생 (strictFunctionTypes: true)let animalHandler: (animal: Animal) => void;let dogHandler: (dog: Dog) => void;animalHandler = dogHandler;// ^^^^^^^^^ Type '(dog: Dog) => void' is not assignable to type '(animal: Animal) => void'// ✅ 올바른 방향dogHandler = animalHandler; // OK
이 옵션은 함수의 타입 안정성을 크게 향상시키지만, 일부 라이브러리와 호환성 문제가 있을 수 있습니다.
bind/call/apply 엄격 체크
기능:
bind, call, apply 메서드의 파라미터 타입 체크
예시:
function greet(name: string, age: number) { console.log(`Hello, ${name}! You are ${age} years old.`);}// ❌ 에러 발생greet.call(null, "Alice", "30");// ^^^^ Argument of type 'string' is not assignable to parameter of type 'number'// ✅ 올바른 타입greet.call(null, "Alice", 30);// ❌ 에러 발생greet.apply(null, ["Alice"]);// ^^^^^^^^^ Argument of type '[string]' is not assignable to parameter of type '[string, number]'// ✅ 올바른 인자 수greet.apply(null, ["Alice", 30]);
클래스 프로퍼티 초기화 필수
기능:
클래스 프로퍼티가 생성자에서 초기화되었는지 확인
예시:
class User { // ❌ 에러 발생 name: string; // ^^^^ Property 'name' has no initializer and is not definitely assigned in the constructor // ✅ 생성자에서 초기화 email: string; constructor(email: string) { this.email = email; } // ✅ 기본값 제공 age: number = 0; // ✅ Optional bio?: string; // ✅ null 허용 avatar: string | null = null; // ✅ Definite assignment assertion (확실한 경우만) id!: number;}
// ❌ noUnusedLocals 에러function greet(name: string) { const message = "Hello"; // 사용되지 않음 // ^^^^^^^ 'message' is declared but its value is never read return name;}// ❌ noUnusedParameters 에러function add(a: number, b: number) { // ^ 'b' is declared but its value is never read return a;}// ✅ 의도적으로 무시할 때는 _ 사용function onClick(_event: MouseEvent) { console.log("Clicked!");}
사용하지 않는 파라미터는 _로 시작하면 경고가 발생하지 않습니다.
모든 경로에서 return 필요
{ "noImplicitReturns": true}
예시:
// ❌ 에러 발생function getStatus(code: number): string { if (code === 200) { return "OK"; } else if (code === 404) { return "Not Found"; } // ^^^^ Not all code paths return a value}// ✅ 모든 경로에서 returnfunction getStatus(code: number): string { if (code === 200) { return "OK"; } else if (code === 404) { return "Not Found"; } return "Unknown";}// ✅ 또는 명시적 에러function getStatus(code: number): string { if (code === 200) { return "OK"; } else if (code === 404) { return "Not Found"; } throw new Error(`Unknown status code: ${code}`);}
Switch문 Fallthrough 방지
{ "noFallthroughCasesInSwitch": true}
예시:
// ❌ 에러 발생function getDay(day: number): string { switch (day) { case 0: return "Sunday"; case 1: console.log("Monday"); // ^^^^ Fallthrough case in switch case 2: return "Tuesday"; default: return "Unknown"; }}// ✅ break 또는 return 추가function getDay(day: number): string { switch (day) { case 0: return "Sunday"; case 1: console.log("Monday"); return "Monday"; // 또는 break; case 2: return "Tuesday"; default: return "Unknown"; }}
catch 블록 변수는 unknown
{ "useUnknownInCatchVariables": true}
예시:
try { throw new Error("Something went wrong");} catch (error) { // error는 unknown 타입 // ❌ 에러 발생 console.log(error.message); // ^^^^^ Object is of type 'unknown' // ✅ 타입 가드 사용 if (error instanceof Error) { console.log(error.message); } // ✅ 타입 단언 (확실한 경우만) const err = error as Error; console.log(err.message);}
any 대신 unknown을 사용하면 타입 체크를 강제할 수 있습니다.
배열/객체 접근 시 undefined 체크
{ "noUncheckedIndexedAccess": true}
예시:
const users = ["Alice", "Bob"];// ❌ 에러 발생 (noUncheckedIndexedAccess)const firstUser = users[0];// ^^^^^^^^^ Type 'string | undefined'const name = firstUser.toUpperCase();// ^^^^^^^^^^^ Object is possibly 'undefined'// ✅ undefined 체크const firstUser = users[0];if (firstUser !== undefined) { const name = firstUser.toUpperCase();}// ✅ Optional 체이닝const name = users[0]?.toUpperCase();// ✅ Non-null assertion (확실한 경우만)const name = users[0]!.toUpperCase();// 객체도 마찬가지type UserMap = { [key: string]: string };const userMap: UserMap = { alice: "Alice" };const user = userMap["alice"];// ^^^^ Type 'string | undefined'
이 옵션은 모든 배열/객체 접근을 T | undefined로 만듭니다. 많은 코드 수정이 필요할 수 있습니다.
interface User { name?: string;}// ❌ 에러 발생const user: User = { name: undefined };// ✅ 프로퍼티 생략const user: User = {};// ✅ 명시적 undefined 허용하려면interface User { name: string | undefined;}
언제 사용:
Optional과 | undefined를 엄격히 구분하고 싶을 때
많은 라이브러리와 호환성 문제가 있을 수 있습니다.
타입 체크 비활성화
특정 상황에서 타입 체크를 우회해야 할 때가 있습니다.
파일 전체
한 줄
타입 단언
// @ts-nocheck// 이 파일의 모든 타입 체크 무시const value = "hello";value = 123; // 에러 발생 안 함
// @ts-ignoreconst value = someUntypedLibrary();// 또는 에러 설명 추가// @ts-expect-error - 외부 라이브러리 타입 불일치const value = someUntypedLibrary();
@ts-ignore 대신 @ts-expect-error를 사용하면 에러가 실제로 발생하지 않을 때 경고를 받을 수 있습니다.
// as를 사용한 타입 단언const value = someValue as string;// Non-null assertionconst element = document.getElementById("root")!;// Double assertion (최후의 수단)const value = someValue as unknown as TargetType;
타입 단언은 타입 안정성을 깨뜨립니다. 정말 확실한 경우에만 사용하세요.
권장 설정
신규 프로젝트
기존 프로젝트
라이브러리
{ "compilerOptions": { // Sonamu 기본 설정 사용 "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "useUnknownInCatchVariables": true, "noUncheckedIndexedAccess": true }}