-
타입스크립트(ZeroCho) Utility Types카테고리 없음 2023. 8. 11. 14:48
Partial 타입 분석
interface Profile { name: string, age:number, married:boolean, } const uri:Profile = { name:'uri', age:29, married:false } const newUri:Profile = { name:'uri', age:29, }
이렇게 이름과 나이는 동일하게 들어가는데 newUri에 결혼유무가 들어가지 않으면 에러가 발생한다.
이걸 인터페이스를 또 만들기에는 이름과 나이가 중복이기 때문에 좋지 않다.
const newUri:Partial<Profile> = { name:'uri', age:29, }
Partial을 사용해주면 다 옵셔널 처리가되어 에러가 사라지게된다.
Partial을 풀어서 코드로 보면 아래 코드로 해석할 수 있다.
type P<T> = { [key in keyof T]?:T[key] } // ⬇️ 분해하면 아래처럼 해석할 수 있다. P<Profile> { name?: age?: married?: }
Pick 타입 분석
interface Profile { name: string, age:number, married:boolean, } const uri:Profile = { name:'uri', age:29, married:false } const newUri:Pick<Profile, 'name'|'age'> = { name:'uri', age:29, }
프로필에서 name이나 age만 가져온다는 의미
interface Profile { name: string, age:number, married:boolean, } type P<T, S extends keyof T> = { [key in S]: T[key] } const uri:Profile = { name:'uri', age:29, married:false } const newUri:Pick<Profile, 'name'|'age'> = { name:'uri', age:29, }
Omit, Exclude, Extract 타입 분석
Exclude
interface Profile { name: string, age:number, married:boolean, } type Name = Profile['name'] const uri:Profile = { name:'uri', age:29, married:false } // Profile에서 married만 뺌 type A = Exclude<keyof Profile, 'married'>
type A 는 'name', 'age'만 남는다.
type Animal = 'Cat' | 'Dog' | 'Human'; type Mammal = Exclude<Animal, 'Human'>
마찬가지고 type Mammal은 Cat, Dog만 남는다.
interface Profile { name: string, age:number, married:boolean, } type Name = Profile['name'] const uri:Profile = { name:'uri', age:29, married:false } type Animal = 'Cat' | 'Dog' | 'Human'; type Mammal = Exclude<Animal, 'Human'> // Profile에서 married만 뺌 type A = Exclude<keyof Profile, 'married'> type O<T, S extends keyof any> = Pick<T,Exclude<keyof T,S>> const newUri:O<Profile,'married'> = { name:'uri', age:29, }
keyof any 는 어떤것이든 키만 들어올 수 있다 라는 의미
type Exclude<T, U> = T extends U ? never : T; type Extract<T, U> = T extends U? T : never;
Exclude T가 U와 같지않은 것만 추려낸다.
Extract T가 U와 같은것만 추려낸다.
타입에는 삼항연산자가 들어갈 수 있다.