Skip to content
Onsite

PartialByKeys<T, K>

MediumP2Coding

Implement PartialByKeys<T, K>: make only the properties named in K optional and keep the rest as they are.

  • K defaults to all keys of T, which makes everything optional.
  • Keys in K that do not exist in T are ignored.
  • The result must be one flat object type, not an intersection.

Tests your type must pass

interface User {
  name: string
  age: number
  address: string
}

interface UserPartialName {
  name?: string
  age: number
  address: string
}

interface UserPartialNameAndAge {
  name?: string
  age?: number
  address: string
}

type cases = [
  Expect<Equal<PartialByKeys<User, 'name'>, UserPartialName>>,
  Expect<Equal<PartialByKeys<User, 'name' | 'unknown'>, UserPartialName>>,
  Expect<Equal<PartialByKeys<User, 'name' | 'age'>, UserPartialNameAndAge>>,
  Expect<Equal<PartialByKeys<User>, Partial<User>>>,
]

Hints

TypeScript
Run and Submit type-check your solution against the tests.