[ts-challenges] Get Return Type / Omit / Readonly
Get Return Type
설계 의도
- 제네릭
T타입을 파라미터가 있는 함수 타입으로 정의하기
- 리턴 타입을 추론하기 위해
infer R를 사용해서 타입 추론 후 리턴하기
코드
/* _____________ Your Code Here _____________ */
type MyReturnType<T extends (...args:any[]) => any> = T extends (...args:any[])=>infer R ? R : never
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<string, MyReturnType<() => string>>>,
Expect<Equal<123, MyReturnType<() => 123>>>,
Expect<Equal<ComplexObject, MyReturnType<() => ComplexObject>>>,
Expect<Equal<Promise<boolean>, MyReturnType<() => Promise<boolean>>>>,
Expect<Equal<() => 'foo', MyReturnType<() => () => 'foo'>>>,
Expect<Equal<1 | 2, MyReturnType<typeof fn>>>,
Expect<Equal<1 | 2, MyReturnType<typeof fn1>>>,
]
Omit
설계 의도
Exclude사용해서 제네릭K타입이 제거된 새로운 키 집합 만들어서 순회하기as키워드 사용해서 키를 제거하는 방식(Key Remapping viaas) 선택
코드
/* _____________ Your Code Here _____________ */
type MyOmit<T, K extends keyof T> = { [P in keyof T as Exclude<P, K>]: T[P]};
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Expected1, MyOmit<Todo, 'description'>>>,
Expect<Equal<Expected2, MyOmit<Todo, 'description' | 'completed'>>>,
Expect<Equal<Expected3, MyOmit<Todo1, 'description' | 'completed'>>>,
]
Readonly
설계 의도
제네릭
K타입이 비어있는 경우 제네릭T의 키 타입을 가지도록 초기값 추가제네릭
K타입의 키인 경우는never로 키 재매핑해서T에서K에 해당하지 않는 속상들에만readonly유지하도록 하기
코드
/* _____________ Your Code Here _____________ */
type MyReadonly2<T, K extends keyof T = keyof T > = {
readonly [P in K] : T[P]
} & {
[P in keyof T as P extends K ? never : P] : T[P]
}
/* _____________ Test Cases _____________ */
import type { Alike, Expect } from '@type-challenges/utils'
type cases = [
Expect<Alike<MyReadonly2<Todo1>, Readonly<Todo1>>>,
Expect<Alike<MyReadonly2<Todo1, 'title' | 'description'>, Expected>>,
Expect<Alike<MyReadonly2<Todo2, 'title' | 'description'>, Expected>>,
Expect<Alike<MyReadonly2<Todo2, 'description' >, Expected>>,
]