[Tyepscript] 10장 고급 타입 Chapter 1

1. 교차 타입 (Intersection Types)

교차 타입은 여러 타입을 결합하여 새로운 타입을 생성하는 방법으로 여러 객체의 속성을 모두 포함하는 타입을 만들 수 있습니다. 

type A = { name: string };
type B = { age: number };

type C = A & B; // C is { name: string; age: number } types

const human: C = {
  name: 'Alice',
  age: 30,
};

console.log(`Name: ${human.name}, Age: ${human.age}`); // Name: Alice, Age: 30

2. 유니언 타입 (Union Types)

유니언 타입은 여러 타입 중 하나의 타입을 허용하는 방식으로, 변수는 정의된 여러 타입 중 하나의 값을 가질 수 있습니다.

function printID(id: number | string | boolean) {
  console.log(`ID: ${id}`);
}

printID(101); // Number Type
printID('James'); // String Type
printID(true); // boolean Type

3. 타입 가드 (Type Guards)

타입 가드는 특정 타입인지를 확인하여 안전하게 타입을 좁히는 방법으로 여러 타입 가드방법들이 있습니다.

  • 타입 서술어 사용하기 (Using type predicates)

타입 서술어는 함수의 반환 타입에 타입 서술어를 사용하는 방법입니다.

type Dog = { bark: () => void };
type Cat = { meow: () => void };

function isDog(animal: Dog | Cat): animal is Cat {
  return (animal as Dog).bark !== undefined;
}

const pet: Dog | Cat = { bark: () => console.log('Woof!') };

if (isDog(pet)) {
  pet.bark(); // 안전한게 Dog 타입으로 사용
}
  • in 연산자 사용하기

in 연산자를 사용하면 객체에 특정 속성이 있는지 확인하여 타입을 좁힐 수 있습니다.

type Dog = { bark: () => void };
type Cat = { meow: () => void };

function getNoise(animal: Dog | Cat) {
  if ('bark' in animal) {
    animal.bark(); // Dog 타입으로 인식되어 안전하게 호출
    console.log('This is Dog');
  } else {
    animal.meow();
    console.log('This is a Cat');
  }
}

const myPet: Dog = { bark: () => console.log('Woof') };
getNoise(myPet);
  • typeof 타입가드

typeof 타입가드를 사용하면 기본 타입을 알 수 있습니다.

function guard(input: number | string | boolean) {
  if (typeof input === 'string') {
    console.log(`문자열 입니다: ${input}`);
  } else if (typeof input === 'boolean') {
    console.log(`숫자 입니다: ${input}`);
  } else {
    console.log(`불리언 입니다: ${input}`);
  }
}

guard('Hello'); // result: 문자열 입니다: Hello
guard(50); // result: 숫자 입니다: 50
guard(true); // result: 불리언 입니다: true
  • instanceof 타입 가드

instanceof 연산자를 사용하여 클래스의 인스턴스인지 확일 할 수 있습니다.

class Computer {}
class Graphics extends Computer {
  graphics() {
    console.log('RTX 5070');
  }
}

function isDesktop(card: Computer): card is Graphics {
  return card instanceof Graphics;
}

const rtx: Computer = new Graphics();

if (isDesktop(rtx)) {
  rtx.graphics(); // 안전하게 Desktop 타입으로 사용
  console.log('My Graphics Card');
}

4. 널러블 타입

널러블 타입은 변수에 null 또는 undefined 값을 허용하는 타입을 정의하는 방법으로, 타입스크립트에서는 strictNullChecks 옵션을 사용해 널러블 타입을 관리할 수 있습니다.

function greet(name?: string) {
  if (name) {
    console.log(`Hello, ${name}`);
  } else {
    console.log(`Hello, Guest!`);
  }
}

greet(); // 선택적 매개변수 사용, "Hello, Guest"
greet('Ko'); // "Hell, Ko"

5. 타입 가드와 타입 단언

타입 단언은 특정 변수의 타입을 강제로 지정하는 방법으로, 타입 가드를 통해 안전하게 타입을 확인하는 것이 좋습니다.

const input: any = 'Hello, TypeScript!';
const strLength: number = (input as string).length; // 타입 단언 사용

// 타입 가드 사용
if (typeof input == 'string') {
  const safeLength: number = input.length; // 안전하게 사용
  console.log(`String length is ${safeLength}`); // String length is 18
}

 

 

GitHub - Koras02/typescript-bloging

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

github.com

 

LIST

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

[Typescript] 12장 선언 병합  (0) 2025.03.12
[Typescript] 11장 고급 타입 Chapter 2  (0) 2025.03.08
[Typescript] 9장 제네릭  (0) 2025.02.24
[Typescript] 8장 열겨형  (0) 2025.02.23
[TypeScript] 7장 클래스  (0) 2025.02.20