본문 바로가기

Study Output for Myself/TypeScript

[Typescript] Utility Types

공식문서: https://www.typescriptlang.org/ko/docs/handbook/utility-types.html

 

Documentation - Utility Types

Types which are globally included in TypeScript

www.typescriptlang.org

Typescript 를 더 잘 활용하고 싶다면 Utility types를 써보도록 하자.

 

Partial<T> 

interface Person {
	name:string;
    age:number;
    favoriteFood:string;
}

const update=(person:Person, updatedData:Partial<Person>) =>{
	return {...person, ...updatedData}
}

const John = {
	name:'John',
    age:12,
    favoriteFood:'Pizza'
}

const upDatedJohn = update(John, {age:14}) // {name:'John', age:14, favoriteFood:'Pizza'}

Person 타입이 가진 속성의 일부(혹은 전체)를 가진 타입을 나타낼 때 사용한다.

객체의 일부 속성을 바꿀 때 인자로 받는 타입으로 유용하다.

 

Required<Type>

interface Shape {
	type?:string;
    diameter?:number;
}

const circle: Required<Shape> = { type:'circle', diameter:12 } //okay
const diamond: Required<Shape> = { type:'diamond' } //error: diameter 속성이 없습니다.

타입의 모든 속성이 꼭 존재해야하는 객체를  나타낼 때 사용한다.

'?'로 옵셔널 속성이어도 Required에서는 모든 속성이 다 요구된다.

 

Readonly<Type>

interface Food {
	type: string;
    price: number;
}

const Kimchi: Readonly<Food> = {
	type: 'Korean',
    price: 12000,
 }

Kimchi.type = 'Italian' //error: Readonly 타입의 객체 속성값을 할당할 수 없습니다.

객체의 값이 수정을 불가능하게 만들 때 사용한다.

JS의 Object.freeze({})와 같은 역할을 한다.

 

Record<KeyType, ValueType>

type Keys = 'name' | 'age' | 'height';

const Human: Record<Keys, string> = {
	name: 'Heather',
   	 age: '12years old',
   	 height: '163cm'
}

객체의 key의 타입과 value의 타입을 명할 때 사용한다.

 

Pick<Type, keys>

interface Any {
	hi: string;
   	 there: string;
   	 nice: string;
}

type Some = Pick<Any, 'hi' | 'nice'>

const example:Some = {
	hi: 'this',
   	 nice: 'is how you do it'
}

타입(Type)에서 특정한 속성(keys)들만 가진 타입을 만든다.

 

Omit<Type, keys>

interface Any {
	hi: string;
   	 there: string;
   	 nice: string;
}

type Deleted = Omit<Any, 'hi' | 'nice'>

const example : Deleted = {
	there:'only there is here'
}

 

타입(Type)에서 특정한 속성(keys)들을 삭제한 타입을 만든다.

 

Exclude<Type, Union>

type A = Exclude< string | number, number > // type A = string

type B = Exclude <'a' |'b' |'c', 'a'|'b' > // type B = 'b'

타입(Type) 중에서 union에 명시된 타입을 삭제한 타입을 만든다.

 

Extract<Type, Union>

type A = Exclude< string | number, number >  // type A = number

type B = Exclude <'a' |'b' |'c', 'a' | 'b' | 'd' | 'e' >  // type B = 'a' | 'b'

타입(Type)과 유니온(Union) 둘 다에 있는 타입만 모은 타입을 만든다.

 

NotNullable<Type>

type A = NotNullable< undefiend | 'a' | 'b' > // type A = 'a' | 'b' 

type B = NotNullable < string[] | null > // type B = string[]

타입(Type)중 undefined 나 null이 아닌 값들만 모은 타입을 만든다. 

 

'Study Output for Myself > TypeScript' 카테고리의 다른 글

[TS] type narrowing, discriminated union  (0) 2023.03.28
[TS] Generic(제네릭)  (0) 2022.07.05
[TS]속성접근자  (0) 2022.07.04
[TS]인터페이스(interface)  (0) 2022.07.02
[TS]타입 알리아스(type alias)  (0) 2022.07.02