Home > Blockchain >  Pass an object parameter then return this object in TypeScript
Pass an object parameter then return this object in TypeScript

Time:01-05

I'm trying to 'extend' a function in TypeScript, but i'm not finding the right way.

const fn1 = function () {
  return {
    extend(obj1: { [name: string]: Function }) {
      return {
        test1() {},
        ...obj1
      }
    }
  }
}
const var1 = fn1().extend({ test2: function () {} });

var1.test1()
var1.test2() // Property 'test2' does not exist on type '{ test1(): void; }'. Did you mean 'test1'?

What can I do to make this work?

CodePudding user response:

It will be enough to add a generic type to extend.

const fn1 = function () {
  return {
    extend<F extends Record<string, Function>>(obj1: F) {
      return {
        test1() {},
        ...obj1
      }
    }
  }
}

F will store the type of the object passed to the function. The compiler is smart enough to compute the correct return type so we don't have to provide one.

const var1 = fn1().extend({ test2: function () {} });
//    ^? const var1: { test1(): void; } & { test2: () => void; }

var1.test1()
var1.test2()

Playground

  • Related