하위 태스크 1
조건부 타입 기본
extends와 삼항 연산자로 조건부 타입 작성
조건부 타입은 type T = A extends B ? C : D의 형태를 가진다. T 타입은 A 타입이 B 타입에 할당 가능한지 검사하여 할당 가능하면 C 타입, 할당 불가능하면 D 타입으로 평가된다.
다음 코드 블록에서 number 타입은 string 타입에 할당할 수 없으므로 A 타입은 string 타입으로 평가된다.
src/conditional-types.ts:
type A = number extends string ? number : string; // string하위 태스크 2
제네릭 + 조건부 타입
타입 변수와 조건부 타입 조합
src/distributive-conditional.ts:
type StringNumberSwitch<T> = T extends number ? string : number;하위 태스크 3
분산적인 조건부 타입
유니온 타입에 조건부 타입 적용
유니온 타입은 조건부 타입에 대해 분배된다. 예를 들어 StringNumberSwitch<A | B>는 StringNumberSwitch<A> | StringNumberSwitch<B>와 같다.
src/distributive-conditional.ts:
// ...
type B = StringNumberSwitch<number | string | null | { name: string }>; // string | number하위 태스크 4 ~ 5
infer 키워드
함수 반환 타입 추출
ReturnType 구현
infer로 ReturnType 직접 구현
src/infer-keyword.ts:
type ReturnType2<T> = T extends (...args: any[]) => infer R ? R : never;
type ReturnWhat = ReturnType2<(() => string) | ((a: string) => number)>; // string | number하위 태스크 6
Partial 사용
모든 프로퍼티를 선택적으로 변환
src/utility-class.ts:
// ...
interface Person {
name: string;
age: number;
}
// { name?: string | undefined; age?: number | undefined; }
type PartialPerson = Partial<Person>;하위 태스크 7
Required 사용
모든 프로퍼티를 필수로 변환
src/utility-class.ts:
// ...
// { name: string; age: number }
type RequiredPerson = Required<PartialPerson>;하위 태스크 8
Readonly 사용
모든 프로퍼티를 readonly로 변환
src/utility-class.ts:
// ...
// { readonly name: string; readonly age: number }
type ReadonlyPerson = Readonly<Person>;하위 태스크 9
Pick 사용
특정 프로퍼티만 선택
src/utility-class.ts:
// ...
// { name: string; }
type PersonWithName = Pick<Person, "name">;하위 태스크 10
Omit 사용
특정 프로퍼티 제외
src/utility-class.ts:
// ...
// { age: number; }
type PersonWithoutName = Omit<Person, "name">;하위 태스크 11
Record 사용
키-값 타입 정의
src/utility-class.ts:
// ...
type PriceRecord = Record<string, number>;
const prices: PriceRecord = {
tomato: 2000,
banana: 3000,
kimchi: 8000,
};하위 태스크 12
Exclude 사용
유니온 타입에서 특정 타입 제외
src/advanced-utilities.ts:
type Animal = Dog | Cat;
type Dog = {
color: string;
height: number;
};
type Cat = {
name: string;
age: number;
};
// { color: string; height: number; }
type DogType = Exclude<Animal, Cat>;하위 태스크 13
Extract 사용
유니온 타입에서 특정 타입만 추출
src/advanced-utilities.ts:
// ...
// { name: string; age: number; }
type CatType = Extract<Animal, Cat>;하위 태스크 14
ReturnType 사용
함수 반환 타입 추출
// ...
function add(a: number, b: number) {
return a + b;
}
type ReturnWhat = ReturnType<typeof add>; // number