#How can I define "custom method" type passed to constructor?

25 messages · Page 1 of 1 (latest)

low musk
#
class foo {
  customAdd?: (foo: unknown) => this
  constructor(customAdd?: (foo: unknown) => this) { // A 'this' type is available only in a non-static member of a class or interface.
    this.customAdd = customAdd
  }
  add(foo: unknown): this {
    if (this.customAdd) {
      return this.customAdd(direction);
    }
    // default add
  }
}

foo have children classes, so this might refer to it's children but not itself, and I don't an as is a proper solution.

#

if I define it as (foo: unknown) => foo, this would happen:

class bar extends foo {}
new Bar(() => new bar()) // this throws, because () => bar is not assignable to () => foo
#

I need foo to be readonly, to make feature like history

#

I need Copying methods but not mutating methods

low musk
#

!helper

mortal vault
#

you need to use "this" parameter of functions

low musk
#

sorry but just like I said before, this could change because there are children classes, Maybe I've understood something wrong, but asserting the type of this might not help as I need to assert it as (this: this)

low musk
#

I need to define a type that is sultable for all children classes

low musk
low musk
#

But anyway, thank you for your help

#

!helper

low musk
#

!helper

mortal vault
#

oh you want it to work with inheritance

low musk
#

yes

low musk
mortal vault
#

my best suggestion is to not use inheritance here sorry u ran into this issue

low musk
#

thanks

#

!resolved

slate fiber
#

what's going on with this helper spam

#

3 times for the same post