0

look this

class Demo<T> {
  get<K extends keyof T>(key?: K): K extends undefined ? Partial<T> : T[K] {
    const res: Partial<T> = {}
    if (key) {
      return res[key]
    } else {
      return res
    }
  }
}

This code does not work

I whant:

  • if key == undefined, return Partial<T>
  • esle return T[K]

How can i do this?

lanten
  • 47
  • 4

1 Answers1

1
function get<T, K extends keyof T>(source: T, key: K): T[K]
function get<T>(source: T, key: undefined): Partial<T>
function get<T>(source: T): Partial<T>
function get<T, K extends keyof T>(source: T, key?: K): T[K] | Partial<T> {
  if (key === undefined) {
    return source
  }
  return source[key]
}

let a = get({ a: 1, b: 2 }, "a")
let b = get({ a: 1, b: 2 }, undefined)
let c = get({ a: 1, b: 2 })

function overload is what you need in this situation Function Overloading

Minami
  • 963
  • 6
  • 21