[Typescript] 유틸리티 타입

Asher Park·2023년 1월 30일
0
post-thumbnail

스파르타코딩클럽 내일배움캠프 Typescript 강의를 들으며 공부한 것을 적은 것입니다.

Partial

  • 특정 타입에 속해있는 Property들을 모두 선택적으로 변환을 해주는 타입.
interface Toppings {
    tomatoes: boolean;
    onion: boolean;
    lettuce: boolean;
    ketchup: boolean;
}

위와 같은 인터페이스가 선언되어 있을 때,

const myToppings: Toppings = {
}

// error
// tomatoes, onion, lettuce, ketchup 속성이 없다 

일반적인 방식으로 type을 지정해 줄 경우, 에러 발생한다.

const partialToppingsWant: Partial<Toppings> = {
}

Partial은 선택적으로 반환 하기 때문에 에러가 발생하지 않는다.


속성이 undefined 가 될 수 있다고 얘기해준다.


Required

  • Partial의 반대.
  • 특정 타입에 속해있는 Property들을 필수로 반환해야 한다.
interface BubbleTeaOrder {
	tea: boolean;
  	straw?: boolean;
}

위와 같은 인터페이스가 선언되어 있을 때,
straw가 ?: 로 필수 사항이 아니지만,

const myBubbleTeaOrder: Required<BubbleTeaOrder> = {
	tea: true,
  	straw: true,
}

위와 같이 straw 를 필수로 true나 false를 반환하도록 한다.


Readonly

  • 한 타입의 Property들을 읽기권한만 가능하게 해주는 타입.
interface BankAccount {
	accountNumber: string;
  	balance: bigint;
}

위와 같은 인터페이스가 선언되어 있을 때,

const myAccount: Readonly<BankAccount> = {
	accountNumber: "1234",
  	balance: BigInt(Number.MAX_SAFE_INTEGER),
};

myAccount 객체를 다음과 같이 선언하면,

myAccount.accountNumber = "123"
// error

읽기 전용이므로 값을 할당 할 수 없다는 에러가 발생한다.


Record

  • 객체 타입을 선언하는데 쓰이는 타입.
type ObjectTypeRecord = Record<string, string>;
type ObjectTypeObject = {
	[x: string]: string
}

// 위의 두개가 동일
type Country = "Korea" | "USA" | "UK";
type CountryCode = 82 | 1 | 44;

type CountryToCountryCode = Record<Country, CountryCode>;

const countries: CountryToCountryCode = {
	Korea: 82,
  	USA: 1,
  	UK: 44,
}

Omit

  • 특정 타입에 있는 Property를 삭제(생략)시킬 때 쓰는 타입.
interface UserInfo {
	userName: string;
  	favoriteColor: string;
  	email: string;
  	password: string;
}

위와 같은 인터페이스가 선언되어 있을 때,

type LessUserInfo = Omit<UserInfo, "email" | "password">;

LessUserInfo 라는 타입을 다음과 같이 정의하면,

위와 같은 형태로 구성되는 것을 알 수 있다.


Exclude

  • 유니언 타입에 속해있는 Property들을 생략할 때 쓰이는 타입.
type MyType = "dog" | "cat";
type ExcludedMyType = Exclude<MyType, "cat">;

const noCat: ExcludedMyType = "cat" // error

Pick

  • 특정 Property들을 뽑아 쓸 수 있도록 해주는 타입.
interface User {
	firstName: string;
  	lastName: string; 
}

interface Student {
	user: User;
  	school: string;
  	grade: number;  	
}

위와 같은 인터페이스가 선언되어 있을 때,

type StudentName = Pick<Student, "user" | "school">;

다음과 같은 타입을 정의했다면,

const studentName: StudentName = {
	user: {
    	firstName: "Asher",
      	lastName: "Park",
    },
  	school: "YU",
};

Student의 인터페이스에서 user Property와 school Property를 뽑아와 사용할 수 있다.


Extract

  • Exclude의 반대!
  • 필요한 유니언만 뽑아온다.
type MyType = "dog" | "cat" | "monkey";
type ExtractedType = Extract<MyType, "dog" | "cat">

const onlyDogOrCatAllowed: ExtractedType = "cat" // 또는 dog만 할당가능

NonNullable

  • 특정 타입에서 null 이나 undefined 타입을 생략해준다.
type QueryParam = string | string[] | undefined | null;
type NonNullableQueryParam = NonNullable<QueryParam>;

const forbiddenQueryParam: NonNullableQueryParam = undefined; // error
profile
배움에는 끝이없다

0개의 댓글