Skip to main content

Command Palette

Search for a command to run...

[ts-challenges] Get Return Type / Omit / Readonly

Published
2 min read

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 via as) 선택

코드

/* _____________ 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>>,
]

More from this blog

Conductor 워크스페이스마다 .env 파일 자동 복사하기

문제를 만나다 개인 프로젝트를 진행할 때 기능을 병렬로 구현하기 위해서 Conductor를 사용하고 있다. 여러 개의 워크 스페이스를 새로 만들 때마다 환경변수를 매번 수동 복사해야 하는 게 매우 귀찮았다. 워크트리 개념이 익숙하지 않아서 처음에는 워크트리 생성 시 모든 파일을 다 가져오는 줄 알았다. 워크트리의 동작 방식을 찾아보니, git에 저장된 파일만 생성된다는 걸 새로 알게 되었다. 도움 받은 블로그 글 링크 : Git에서 다수...

Dec 28, 20251 min read

[ts-challenges] Includes / Push / Unshift / Parameters

Includes 설계 의도 튜플 타입 T를 첫 번째 요소인 Head와 나머지 요소들인 Tail로 분리해서 추론한다. Head가 제네릭 U 타입과 동일하지 않으면 Includes 타입을 Tail에 대해 재귀적으로 다시 실행하면서 다음 요소 검사하기 boolean 타입의 경우, true와 false이 모두 할당가능하니까 엄격하게 동등한지 비교하기 위해서 Equal 헬퍼함수 사용 코드 type Equal<X, Y> = (<T>() => ...

May 23, 20253 min read

Untitled Publication

37 posts