Today I Learned_230418
TypeScript
- Omit
    
- 여러 속성 중 하나를 없애기
 - Partial보단 Pick, Omit 사용하자
 - Pick과 Exclude로 이루어짐
 
 
// K는 키값들만 와야 함
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
const newheejung2: Omit<Profile, 'married'> = {
    name: 'heejung',
    age: 29,
}
keyof any가 무슨 뜻일까? → 잘못된 타입을 넣어 보면 알 수 있다.
Omit의 두번째 인자에 키값이 아닌 값을 넣으면 에러가 난다.
- Exclude
 
// T에서 U타입을 빼는 것
// T가 U의 부분집합이면 없애버리고, 아니면 T를 남긴다.
type Exclude<T, U> = T extends U ? never : T;
type Animal = 'Cat' | 'Dog' | 'bird';
type Mammal = Exclude<Animal, 'bird'> // 'Cat' extends 'bird'는 false이므로 남아있는다
여러 개를 돌면서(3개) 맞으면 다음껄로 넘어가고.. 이렇게 반복된다.
- Extract
 
type Extract<T, U> = T extends U ? T : never;
Exclude와 Extract는 서로 반대가 된다.
삼항 연산자와 제네릭을 사용해서 타입을 만들 수 있다.
infer가 들어갈 때 부터 삼항 연산자 사용..
- Required
    
- 옵셔널한것을 필수로 바꾸는 것
 
 
interface Profile {
    name?: string,
    age?: number,
    married?: boolean,
}
//Profile을 전부 필수로 바꾸려면 Require<Profile>과 같이 사용
type Required<T> = {
    [P in keyof T]-?: T[P];
};
- -는 modifier. optional을 전부 빼버리는 것
 - +?도 있지만 굳이 사용하진 않는다.
 - 
    
남의 타입 가져올 때 ? 떼고 가져오고 싶으면 이거 사용하면 된다.
 - ReadOnly
    
- 수정 못하게 막고싶을 때
 
 
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};
const heejung: Readonly<Profile> = {
    name: 'heejung',
    age: 29,
    married: true,
}
heejung.name = '12345'  //불가
readonly를 이렇게 붙일 수도 있음
interface Profile {
    readonly name: string,
    readonly age: number,
    readonly married: boolean,
}
// 이렇게 하면 readonly가 빠진다
type R<T> = {
    -readonly [Key in keyof T]-?: T[Key];
}
남의꺼 가져올 때 modifier를 통해서 떼버릴수가 있음
- Record
    
- 객체를 표현하는 방법
 
 
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
인덱스드 시그니처를 이용하면 이렇게 표현할 수 있음
interface Obj {
    [key: string]: number;
}
const a: Obj = {a: 3, b: 5, c: 7}
Record를 사용하면 더 간단하게 표현 가능
const b: Record<string, number> = {a: 3, b: 5, c: 7}
객체의 key는 string | number | symbol만 올 수 있음
이걸 가져오기 위해 extends keyof any 사용
- NonNullable
    
- null과 undefined를 뺀 타입을 가져오고 싶을 때 사용
 
 
type NonNullable<T> = T extends null | undefined ? never : T;
type A = string | null | undefined | boolean | number;
// A에서 null과 undefined를 뺀 타입을 가져오고 싶을 때
type B = NonNullable<A>;
타입들은 키에 적용되는 타입도 있고 인터페이스(객체)에 적용되는 타입도 있다.
Partial, Required, ReadOnly, Pick은 인터페이스에 적용
Exclude, Extract는 key들에 적용된다.
NonNullable은 key에 적용되는 것들