본문 바로가기
IT/typescript

TS - Exclude<T, U>

by 내일은교양왕 2023. 6. 27.

개념
한마디로, T에서 U를 제외시킨 Type
U를 제외시킬 수 없다면 T 그대로 리턴
T에 union type 받을 수 있음

type Exclude<T, U> = T extends U ? never : T

 

Examples

Only number

type numberOnly = Exclude<string | number, string>
const a: numberOnly = 5
// const a: number

how it works

Exclude<string | number, number>
    => Exclude<string, number> | Exclude<number, number>
    => string | never =>
    => string

 

Remove props in interface

interface Student {
  name: string
  age: number
  address: string
  gpa: number
}


type refiendStudent = Exclude<keyof Student, 'address'>
//type refiendStudent = "name" | "age" | "gpa"


Remove itself

type neverType = Exclude<string, string>
// type neverType = never

 

 

참고
https://velog.io/@ggong/Typescript의-유틸리티-타입-1-Record-Extract-Pick
https://stackoverflow.com/questions/56916532/difference-b-w-only-exclude-and-omit-pick-exclude-typescript

'IT > typescript' 카테고리의 다른 글

[Typescript] enum vs union  (0) 2024.02.05
TS - 5.0 New features  (0) 2023.07.01
TS - unknown vs any  (0) 2023.06.27
TS - never  (0) 2023.06.27
TS - Extract<T, U>  (0) 2023.06.27