Home > Net >  Declare explicit types for a dynamically created class function
Declare explicit types for a dynamically created class function

Time:12-28

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.

CodePudding user response:

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

  • Related