Advanced Typing Concepts

Juhwan Lee·2022년 5월 9일
0

Learning TypeScript

목록 보기
4/5
post-thumbnail
  • Intersection Types
  • Type Guards
  • Discriminated Unions
  • Type Casting
  • Function Overloads

✅ Intersection Types (인터섹션 타입)

  • type 묶기
type Admin = {
  name: string;
  privileges: string[];
};

type Employee = {
  name: string;
  startDate: Date;
};

type ElevatedEmployee = Admin & Employee;
  • interface도 가능하다
type Admin = {
  name: string;
  privileges: string[];
};

type Employee = {
  name: string;
  startDate: Date;
};

interface ElevatedEmployee extends Admin, Employee {}

// interface Admin, interface Employee로 선언을 해도 동일하게 가능
  • 더욱 간결하게 적용
type Combinable = string | number;
type Numeric = number | boolean;

type Universal = Combinable & Numeric;

✅ Type Guards (타입 가드)

타입가드는 특정 속성이나 메소드를 사용하기 전에 그것이 존재하는지 확인하거나, 타입을 사용하기 전에 이 타입으로 어떤 작업을 수행할 수 있는지를 확인하는 방식이다.

type Admin = {
  name: string;
  privileges: string[];
};

type Employee = {
  name: string;
  startDate: Date;
};

type UnknownEmployee = Employee | Admin;

// ❌ type err 
function printEmployeeInformation(emp: UnknownEmployee) {
  console.log('Name: ' + emp.name)
	if (typeof emp === 'object') {
		console.log('Privileges: ' + emp.privileges)
  }
}

// ⭕ possible
function printEmployeeInformation(emp: UnknownEmployee) {
  console.log('Name: ' + emp.name)
  if ('privileges' in emp) {
    console.log('Privileges: ' + emp.privileges)
  }
	if ('startDate' in emp) {
    console.log('Start Date: ' + emp.startDate);
  }
}

printEmployeeInformation(e1);
printEmployeeInformation({ name: 'Manu', startDate: new Date() });
  • class 에서 instanceof 사용
class Car {
  drive() {
    console.log('Driving...');
  }
}

class Truck {
  drive() {
    console.log('Driving a truck...');
  }

  loadCargo(amount: number) {
    console.log('Loading cargo.. ' + amount);
  }
}

type Vehicle = Car | Truck;

const v1 = new Car();
const v2 = new Truck();

function useVehicle(vehicle: Vehicle) {
  vehicle.drive();
  if (vehicle instanceof Truck) {
    vehicle.loadCargo(1000);
  }
}

useVehicle(v1);
useVehicle(v2);

✅ Discriminated Unions

작업시 사용할 수 있는 객체와 유니언 타입을 이용하는 패턴

interface Bird {
  type: 'bird'; //✨추가
  flyingSpeed: number;
}

interface Horse {
  type: 'horse'; //✨추가
  runningSpeed: number;
}

type Animal = Bird | Horse;

function moveAnimal(animal: Animal) {
  let speed;
  switch (animal.type) {
    case 'bird':
      speed = animal.flyingSpeed;
      break;
    case 'horse':
      speed = animal.runningSpeed;
  }
  console.log('Moving at speed: ' + speed);
}

moveAnimal({ type: 'bird', flyingSpeed: 10 });

✅ Type Casting(형 변환)

타입스크립트가 직접 감지하지 못하는 특정 타입의 값을 타입스크립트에 알려주는 역할

// 1번째
const userInputElement = <HTMLInputElement>document.getElementById('user-input')!;
// 2번째
const userInputElement = document.getElementById(
  'user-input'
)! as HTMLInputElement;

userInputElement.value = 'Hi there!';

확실할 경우 ‘!’를 사용하지만 확실하지 않은 경우

const userInputElement = document.getElementById(
  'user-input'
);

if (userInputElement) {
  (userInputElement as HTMLInputElement).value = 'Hi there!';
}

✅ Index property (인덱스 속성)

interface ErrorContainer { // { email: 'Not a valid email', username: 'Must start with a capital chracter'}
  [prop: string]: string;
}

const errorBag: ErrorContainer = {
  email: 'Not a valid email!',
  username: 'Must start with a capital character!'
}

✅ Function Overloads (함수 오버로드)

동일한 함수에 여러 함수를 정의할 수 있는 기능

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: string, b: number): string;
function add(a: number, b: string): string;
function add(a: Combinable, b: Combinable) {
  if (typeof a === 'string' || typeof b === 'string') {
    return a.toString() + b.toString();
  }
  return a + b;
}

const result = add('Juhwan', 'Lee');
result.split(' ');

✅ Optional Chaining (옵셔널 체이닝)

const fetchedUserDate = {
  id: 'u1',
  name: 'Juhwan',
  job: { title: 'DEVELOPER', dexcription: 'Front-end' },
};

console.log(fetchedUserDate.job?.title);

✅ Nullish coalescing (null 병합 연산자)

const userInput = null;

const storedData = userInput ?? 'DEFAULT'

undefined나 ‘’ 빈 문자열인 경우 그대로 나오지만 null 일경우 ‘DEFAULT’가 나오게 된다.

고급 타입 관련 추가 정보

profile
keep going

0개의 댓글