Skip to content

43 - Exclude #6

Description

@DEV4N4
// your answers
type MyExclude<T, U> = Omit<T, U>; // failed
type MyExclude<T, U> =  T extends U ? never : T; // answers

참고하면 좋은 블로그

Omit<T, U>를 사용하여 Exclude<T, U>를 구현할 수 없는 이유는 Omit<T, U>와 Exclude<T, U>의 개념과 동작 방식이 다르기 때문입니다. 이를 자세히 설명하겠습니다.

1. Exclude<T, U>의 역할

Exclude<T, U>는 유니언 타입에서 U에 해당하는 타입들을 제거하는 타입 유틸리티입니다.

예를 들어:

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

여기서 'a'를 제거하고 'b' | 'c'만 남깁니다.

2. Omit<T, U>의 역할

Omit<T, U>는 객체 타입에서 U에 해당하는 키를 제거한 객체를 반환하는 타입 유틸리티입니다.

예를 들어:

type ObjectType = { a: string; b: number; c: boolean };
type Result = Omit<ObjectType, 'a'>; 
// { b: number; c: boolean }

'a'라는 속성 키가 제거된 객체 타입을 반환합니다.

3. 주요 차이점

Exclude는 유니언 타입을 다룬다: 타입의 집합에서 특정 타입을 제거합니다.
Omit은 객체 타입을 다룬다: 객체의 특정 속성을 제거합니다.

4. 왜 Omit으로 Exclude를 구현할 수 없는가?

Omit은 객체 타입을 다루므로, 유니언 타입과는 호환되지 않습니다. 예를 들어, 'a' | 'b' | 'c'와 같은 유니언 타입은 객체가 아니기 때문에 Omit<'a' | 'b' | 'c', 'a'>는 문법적으로도 유효하지 않습니다.

MyExclude<T, U> 구현
다음은 Exclude를 직접 구현한 예시입니다:

type MyExclude<T, U> = T extends U ? never : T;

T extends U는 T가 U에 속하는지 확인합니다.
속한다면 never을 반환하여 제거합니다.
속하지 않는다면 T를 그대로 유지합니다.

type Result = MyExclude<'a' | 'b' | 'c', 'a'>; 
// 'b' | 'c'

이 구현은 Exclude와 동일하게 작동합니다.

결론

Omit은 객체 타입에 사용되므로 유니언 타입을 처리하는 Exclude를 구현할 수 없습니다. 따라서 Exclude의 직접적인 구현 방식이 필요합니다.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    answerShare answers/solutions to a question

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions