Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Declare explicit types for a dynamically created class function

Say I’ve got this class:

class Foo {
  bar = this.createDynamicFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createDynamicFunction((param: number) => {
    return 1 + param;
  });

  createDynamicFunction(fn: (param: any) => any) {
    return (param) => fn(param);
  }
}

const foo = new Foo()
foo.bar('baz') // => barbaz
foo.baz(2) // => 3

How do I declare types for the functions Foo.prototype.bar and Foo.prototype.baz? I want to explicitly say that bar and baz accept and return string and number respectively.

I realize that this is a contrived example. For some context, I’m in the final stages of rewriting one of my message queue client libraries and a lot of the class functions are dynamically created. These functions share a lot of functionality, but their inputs/outputs differ.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Generics are made for this:

class Foo {
  bar = this.createDynamicFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createDynamicFunction((param: number) => {
    return 1 + param;
  });

  createDynamicFunction<Type>(fn: (param: Type) => Type) {
    return (param : Type) => fn(param);
  }
}

const foo = new Foo()
//console.log(foo.baz(2)) // => 3
console.log(foo.bar('baz')) // => barbaz
console.log(foo.baz(2)) // => 3

You create a generic function, for which the type can be anything. And you can define your overall function type based on that type

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading