TypeScriptⅡ(Utility types)

EunRyeong Park·2022년 9월 24일
0

typescript

목록 보기
2/11

Utility types
공통 타입 변환을 용이하게 하기 위해 제공
-전역으로 사용이 가능함

• Partial

property를 선택적으로 만드는 타입을 구성
->주어진 타입의 모든 하위 타입 집합(부분집합)을 나타내는 타입을 return

//Partial<T>
  
interface Todo {
  title: string;
  description: string;
}
  
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Tod
o>) {
	return { ...todo, ...fieldsToUpdate };
}
  
const todo1 = {
  title: 'organize desk',
  description: 'clear clutter',
};
  
const todo2 = updateTodo(todo1, {
  description: 'throw out trash',//title을 제외한 description만 호출해서 사용
});

• Readonly

property를 읽기전용으로 설정한 타입

//Readonly<T>
  
interface Todo {
  title: string;
}
const todo: Readonly<Todo> = {
  title: 'Delete inactive users',
};

todo.title = 'Hello'; 
// Error: Cannot as sign to 'title' because it is a read-only property
// =>frozen된 객체의 속성을 재할당하거나 하여 런타임에러가 나는것을 방지

• Record<K,T>

Property 타입을 집합K로, value 타입을 T로 지정
->특정 property를 다른 타입으로 매핑하고 싶을때 유용함

//Record<K,T>
  
interface PageInfo {
  title: string;
 }
  
type Page = 'home' | 'about' | 'contact';
  
const x: Record<Page, PageInfo> = {
  about: { title: 'about' },
  contact: { title: 'contact' },
  home: { subTitile: 'home' },
  // Error: '{ subTitile: string; }' is not assigna
  ble
  main: { title: 'home' },
// Error: main is not assignable to type 'Page'.
};
  
// 객체 x는 key타입이 'home' | 'about' | 'contact'여야 하고
// Value타입이 pageInfo여야함

• Pick<T,K>

타입에서 특정 property들인 K의 집합을 선택해 구성한 타입 지정

// Pick<T,K>

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
type TodoPreview = Pick<Todo, 'title' | 'completed
'>;
const todo: TodoPreview = {
  title: 'Clean room',
  completed: false,
  description: 'description’
// Error: 'description' is not assignable to type
//  pick에서 선택되지 않은 description이 선택되어서 error발생
};

• Omit<T,K>

모든 프로퍼티를 선택한 다음 K를 지운 타입을 구성함

// Omit<T,K>

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
description: 'description' 
// Error: 'description' is not assignable to type
// Omit으로 description을 지웠기 때문
};

• Exclude<T,U>

T에서 U에 할당할 수 있는 모든 속성을 제외한 타입을 구성

// Exclude<T,U>
type T0 = Exclude<"a" | "b" | "c", "a">;// "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;// "c"
type T2 = Exclude<string | number | (() => void), Function>; 
// string | number
                                     
// 비유가 적절할지는 모르겠지만 차집합느낌..?

• Extract<T,U>

T에서 U에 할당할 수 있는 모든 속성을 추출하여 타입을 구성

// Extract<T,U>

type T0 = Extract<"a" | "b" | "c", "a" | "f">;// "a"
type T1 = Extract<string | number | (() => void), Function>; 
// () => void
                                     
// 비유가 적절할지는 모르겠지만 교집합느낌..?

• NonNullable

null과 undefined를 제외한 타입

// NonNullable<T>
  
type T = NonNullable<string[] | null | undefined>; // string[]

• Parameters

함수타입인 T의 파라미터들의 타입을 Tuple로 구성

// Parameters<T>
declare function f1(arg: { a: number, b: string
}): void
type T0 = Parameters<() => string>; // [] (튜플)
type T1 = Parameters<(s: string) => void>; // [string]
type T2 = Parameters<(<T>(arg: T) => T)>; // [unknown]
type T4 = Parameters<typeof f1>; // [{ a: number, b: string }]
type T5 = Parameters<any>; // unknown[]
type T6 = Parameters<never>; // never
type T7 = Parameters<string>; // 함수의 매개변수가 선언되어있지 않아서 오류
type T8 = Parameters<Function>; // 함수의 매개변수가 선언되어있지 않아서 오류

• ConstructorParameters

생성자 함수의 모든 매개변수(파라미터)들의 타입을 추출
모든 매개변수 타입을 가지는 튜플타입을 생성
만약 T가 함수가 아니라면 type은 never

// ConstructorParameters<T>
interface I1 {
	new(args: string): Function;
}
type T12 = ConstructorParameters<I1>; // [string]
function f1(a: T12) {
  a[0]
  a[1] 
// Error: Tuple type '[args: string]' of length '1' has no element at index '1'.
}

• ReturnType

함수 T의 return 타입으로 구성된 타입을 생성

// ReturnType<T>
type T0 = ReturnType<() => string>; // string
type T1 = ReturnType<(s: string) => void>; // void
type T2 = ReturnType<(<T>() => T)>; // {}
type T3 = ReturnType<(<T extends U, U extends numbe
r[]>() => T)>; // number[]
type T4 = ReturnType<any>; // any
type T5 = ReturnType<never>; // any
type T6 = ReturnType<string>; // return 타입이 구성되어있지 않아서 오류
type T7 = ReturnType<Function>; // return 타입이 구성되어있지 않아서 오류

• Required

모든 T의 property가 필수로 설정된 타입을 구성

// Required<T>
interface Props {
  a?: number;
  b?: string;
};
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };
// Error: Property 'b' is missing in type '{ a:number; }'
// b 프로퍼티를 설정하지 않아서 에러

• InstanceType

생성자 함수 T의 instance 타입을 구성

// InstanceType<T>
class C {
  x = 0;
  y = 0;
} 
type T0 = InstanceType<typeof C>;  // C
type T1 = InstanceType<any>;  // any
type T2 = InstanceType<never>;  // any
type T3 = InstanceType<string>;  // Error
type T4 = InstanceType<Function>;  // Error

0개의 댓글