TypeScript의 Utility Type 정리

yj j·2024년 2월 20일

Partial

Type의 모든 property를 선택적으로 타입 생성합니다. 주어진 타입의 모든 부분집합을 리턴합니다.

interface Todo {
  title: string;
  description: string;
  a:string;
  b:string;
  c:string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
  title: "organize desk",
  description: "clear clutter",
  a:"a test",
  b:"b test",
  c:"c test",
};

const todo2 = updateTodo(todo1, {
  description: "throw out trash",
  b:"b is b"
});


Required

Type집합의 모든 property를 필수 타입으로 지정합니다.

interface Props {
  a?: number;
  b?: string;
}

const obj: Props = { a: 5 };

const obj2: Required<Props> = { a: 5 };  //에러 발생, b도 필수 타입으로 지정됨


ReadOnly

모든 property를 읽기 전용으로 만듭니다. 한 번 할당한 값은 재할당 할 수 없습니다.

interface Todo {
  title: string;
}
 
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};
 
todo.title = "Hello";
//Cannot assign to 'title' because it is a read-only property.


Pick

특정 타입에서 몇 개의 property를 선택해 타입을 정의합니다.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
//Todo에서 title과 completed만 가져온 타입 생성
type TodoPreview = Pick<Todo, "title" | "completed">; 
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};
 


Omit

특정 property만 제거한 타입을 정의합니다. pick과는 반대입니다.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
//Todo에서 description을 제외한 타입 생성
type TodoPreview = Omit<Todo, "description">;  
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};


Exclude<T, ExcludedUnion>

ExcludedUnion에 할당할 수 있는 모든 유니온 멤버를 Type에서 제외하여 타입을 생성합니다.

//a를 제외한 타입 생성 type T0 = "b"|"C"
type T0 = Exclude<"a" | "b" | "c", "a">;

//a,b 를 제외한 타입 생성 type T0 = "C"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;

//type T2 = string | number
type T2 = Exclude<string | number | (() => void), Function>;


ReturnType

반환 타입을 지정합니다.
입력 파라미터의 시그니처와 동기화할 때 자주 쓰입니다.

function sendData(a: number, b: number) {
    return {
        a: `${a}`,
        b: `${b}`
    }
}
type Data = ReturnType<typeof sendData>


출처
https://www.typescriptlang.org/ko/docs/handbook/utility-types.html#returntypetype
https://fjolt.com/article/typescript-returntype-utility-type

profile
꿈꾸는 사람

0개의 댓글