TypeScript

Jihyo Jeon·2023년 2월 14일
0

soju-study

목록 보기
4/4
post-custom-banner

Type Aliases vs. Interface


In TypeScript, type aliases and interfaces are very similar. Both can be extended(type aliases: from v2.7) and implemented but only interface can do declaration merging.

type Owl = {nocturnal: true} & BirdType
type Robin = {nocturnal: false} & BirdInterface

interface Peacock extends BirdType {
  colorful: true
  flies: false
}
interface Chicken extends BirdInterface {
  colorful: false
  flies: false
}

let owl: Owl = {wings: 2, nocturnal: true}
let chicken: Chicken = {wings: 2, colorful: false, flies: false}

// interface
interface Point {}
class SomePoint implements Point {}

// type alias
type Point = {}
class SomePoint implements Point {}

// Error: can not implement a union type
type PartialPoint = {x: number} | {y: number}
class SomePartialPoint implements PartialPoint {}

interface Point {
  x: number
}
interface Point {
  y: number
}
const point: Point = {x: 1, y: 2}

Utility Type

Partial

interface Address {
  email: string;
  address: string;
}

type MayHaveEmail = Partial<Address>;
const me: MayHaveEmail = {};
const you: MayHaveEmail = { email: 'test@abc.com' };
const all: MayHaveEmail = { email: 'capt@hero.com', address: 'Pangyo' };

Pick

interface Hero {
  name: string;
  skill: string;
}
const human: Pick<Hero, 'name'> = {
  name: 'noname',
};

Omit

interface AddressBook {
  name: string;
  phone: number;
  address: string;
  company: string;
}
const phoneBook: Omit<AddressBook, 'address'> = {
  name: 'J',
  phone: 12342223333,
  company: 'abc'
}
const chingtao: Omit<AddressBook, 'address'|'company'> = {
  name: 'S',
  phone: 44455557777
}

Mapped Type

type Subset<T> = {
  [K in keyof T]?: T[K];
}
interface UserProfile {
  username: string;
  email: string;
  profilePhotoUrl: string;
}

// ❌
interface UserProfileUpdate {
  username?: string;
  email?: string;
  profilePhotoUrl?: string;
}

// option 1 ✅
type UserProfileUpdate = {
  username?: UserProfile['username'];
  email?: UserProfile['email'];
  profilePhotoUrl?: UserProfile['profilePhotoUrl'];
}

// option 2 ✅
type UserProfileUpdate = {
  [p in 'username' | 'email' | 'profilePhotoUrl']?: UserProfile[p]
}

// The Best!👍 ✅
type UserProfileUpdate = {
  [p in keyof UserProfile]?: UserProfile[p]
}
profile
Software Engineer in London, UK
post-custom-banner

0개의 댓글