원시 타입과 리터럴 타입

2025. 4. 4. 16:23프론트엔드/TypeScript(공부)

728x90
---

## 🔹 1. 원시 타입 (Primitive Types)

### 📌 특징

- **단일 값만 저장 가능**: 숫자, 문자열, 논리값 등.
- **엄격한 타입 검사**: 지정된 타입 외 값은 할당할 수 없음.

### 📦 종류별 설명

#### ✅ number 타입
- 모든 숫자 값 포함: 정수, 소수, `Infinity`, `NaN` 등.

```ts
let num1: number = 123;
let num2: number = -123;
let num3: number = 0.123;
let num4: number = Infinity;
let num5: number = NaN;

num1 = 'hello';         // ❌ 오류
num1.toUpperCase();     // ❌ 오류

 


✅ string 타입

  • 문자열 표현 (큰따옴표, 작은따옴표, 백틱 모두 가능)
let str1: string = "hello";
let str2: string = 'hello';
let str3: string = `hello`;
let str4: string = `hello ${str1}`;

✅ boolean 타입

  • 논리형 값 true 또는 false
let bool1: boolean = true;
let bool2: boolean = false;

✅ null 타입

  • null 값만 허용
let null1: null = null;

✅ undefined 타입

  • undefined 값만 허용
let unde1: undefined = undefined;

⚠️ null 값을 다른 타입에 할당하려면?

let numA: number = null; // ❌ 기본 설정에선 오류 발생

해결 방법:

tsconfig.json에서 strictNullChecks 옵션을 꺼야 함.

{
  "compilerOptions": {
    "strictNullChecks": false
  }
}

기본값은 true, 즉 null에 대한 타입 검사를 엄격히 적용합니다.


🔸 2. 리터럴 타입 (Literal Types)

📌 특징

  • 특정 값 하나만 허용하는 타입
  • 해당 값 외 다른 값은 할당 불가

🧪 예제

let numA: 10 = 10;              // 숫자 리터럴 타입
let strA: "hello" = "hello";    // 문자열 리터럴 타입
let boolA: true = true;         // 불리언 리터럴 타입
let boolB: false = false;

✅ 요약 정리

구분 설명

원시 타입 number, string, boolean, null, undefined
리터럴 타입 특정 값만 가능한 타입 (10, "hello", true 등)
null 검사 strictNullChecks: true로 설정 시, 엄격하게 체크함

728x90