[Typescript] 11장 고급 타입 Chapter 2

1. 열거형 맴버 타입 (Enum Member Types)

열거형(Enums)은 상수 집합을 정의하는 데 사용되며, 기본적으로 숫자 또는 문자열 타입을 가집니다.

enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}

// 열거형 맴버 타입 사용
let direction: Direction = Direction.Up;
console.log(direction); // 1

2. 판별 유니언 (Discriminated Unions)

판별 유니언은 서로 다른 타입의 객체를 하나의 타입으로 처리할 수 있으며, 특정 속성으로 어떤 타입인지 구분할 수 있습니다. 안전한 검사를 통해 안전하게 사용할 수 있습니다.

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rectangle'; width: number; height: number };

function area(shape: Shape) {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'rectangle':
      return shape.width * shape.height;
  }
}

const myShape: Shape = { kind: 'circle', radius: 10 };
console.log(area(myShape)); // 314.159...

3. 인덱스 타입(Index Types)

인덱스 타입은 객체의 특정 프로퍼티의 타입을 추론하는 데 사용되며, 인덱스 시그니처를 이용해 객체의 프로퍼티를 동적으로 정의할 수 있습니다.

interface StringArray {
  [index: number]: string;
}

let InArray: StringArray = ['Hello', 'World'];
console.log(InArray[0]); // "Hello"

4. 매핑 타입 (Mapped Types)

매핑 타입은 기존 타입을 기반으로 새로운 타입을 생성하는 데 사용되며, 매핑 타입의 추론을 통한 타입 변형이 가능합니다.

type Hambuger = {
  name: string;
  calories: number;
  protein: number;
  fat: number;
  sodium: number;
};

// Readonly 매핑 타입
type ReadonlyHambuger = {
  readonly [K in keyof Hambuger]: Hambuger[K];
};

const hambuger: ReadonlyHambuger = {
  name: '맥스파이시 상하이 투움바',
  calories: 489,
  protein: 10,
  fat: 6,
  sodium: 1169,
};

console.log(hambuger.calories);
hambuger.calories = 488; // 오류 발생: 읽기 전용 속성

5.조건부 타입 (Conditional Types)

조건부 타입은 타입을 조건에 따라 결정할 수 있게 해줍니다, 분산 조건부 타입을 사용해 복잡한 타입 변환을 수행합니다.

type IsString<T> = T extends string ? 'Yes' : 'No';

type Result1 = IsString<string>; // "Yes"
type Result2 = IsString<number>; // "No"

const result1: Result1 = 'Yes';
const result2: Result2 = 'No';

console.log('Is String Result:', result1); // 출력: Is String Result: Yes
console.log('Is Number Result:', result2); // 출력: Is Number Result: No

6. 조건부 타입의 타입 추론

조건부 타입을 사용하여 타입을 추론하고 출력하는 방법입니다.

// 조건부 타입의 타입 추론
type ExtractType<T> = T extends (infer U)[] ? U : T;

type ArrayType = ExtractType<number[]>; // number
type SingleType = ExtractType<number>; // number

const array: number[] = [1, 2, 3]; // number [] 타입
const singlenumber: number = 42;

console.log('Extracted Array Type:', array);
console.log('Extracted Single Type:', singlenumber);

7. 미리 정의된 조건부 타입

미리 정의된 조건부 타일을 사용해 타입을 생성하고 출력하는 방법입니다.

// 타입 정의
type MixedType = string | number | null | undefined;

// Exclude 사용 예
type Excluded = Exclude<MixedType, string>; // number | null | undefined

// Extract 사용 예
type Extracted = Extract<MixedType, string>; // string

// NotNullable 사용 예
type NonNullableType = NonNullable<MixedType>; // number

// Return Type 사용 예
type Func = () => string;
type FuncReturn = ReturnType<Func>; // string

// instanceType 사용 예
class Animal {
  species: string;
  constructor(species: string) {
    this.species = species;
  }
}

type AnimalInstance = InstanceType<typeof Animal>; // Animal 인스턴스 타입

// 실제 값 할당
const exampleNumber: Excluded = null; // number | null | undefined 타입
const exampleString: Extracted = 'Hello World'; // string 타입
const exampleNonNullable: NonNullableType = 42; // number 타입
const exampleFunc: FuncReturn = 'Return value'; // string
const dog: AnimalInstance = new Animal('Horse'); // Animal 인스턴스

// 출력
console.log('Excluded Type Example:', exampleNumber); // result: Excluded Type Example: null
console.log('Extracted Type Example:', exampleString); // result: Extracted Type Example: Hello World
console.log('NonNullable Type Example:', exampleNonNullable); // result: NonNullable Type Example: 42
console.log('Function Return Example:', exampleFunc); // result: Function Return Example: Return Type
console.log('Animal Instance Example:', dog.species); // result: Animal Instance Example: Horse

 

 

GitHub - Koras02/typescript-bloging

Contribute to Koras02/typescript-bloging development by creating an account on GitHub.

github.com

 

LIST

'Front-End > TypeScript' 카테고리의 다른 글

[Typescript] 13장 데코레이터  (0) 2025.03.14
[Typescript] 12장 선언 병합  (0) 2025.03.12
[Tyepscript] 10장 고급 타입 Chapter 1  (0) 2025.03.06
[Typescript] 9장 제네릭  (0) 2025.02.24
[Typescript] 8장 열겨형  (0) 2025.02.23