@oazmi/kitchensink - v0.9.13
    Preparing search index...

    Function constructFrom

    • use the constructor of a class's instance to construct a new instance.

      this is useful for avoiding pollution of code with new keyword along with some wonky placement of braces to make your code work.

      Type Parameters

      • T
      • Args extends any[] = any[]

      Parameters

      • class_instance: T
      • ...args: Args

      Returns T

      class K {
      value: number

      constructor(value1: number, value2: number) {
      this.value = value1 + value2
      }
      }

      const a = new K(1, 1)
      const b = constructFrom(a, 2, 2) // equivalent to `const b = new K(2, 2)`

      // vanilla way of constructing `const c = new K(3, 3)` using `a`
      const c = new (Object.getPrototypeOf(a).constructor)(3, 3)

      a satisfies K
      b satisfies K
      c satisfies K