0

I am looking for a way to set a name string within a class and use it in the abstract class at the constructor level, meaning not within a function. I can't open up constructor because I am using typedi.

Here's the playground link.

Uncaught TypeError: this.name is not a function

abstract class Root {
    abstract name(): string
    notFoundError = new Error(`${this.name()} not found`)

}

class Use extends Root {
    name = () => 'User'
}

const x = new Use()
throw x.notFoundError

I am not looking for this:

abstract class Root {
    abstract name: string
    notFoundError = () => new Error(`${this.name} not found`)

}

class Use extends Root {
    name = 'User'
}

const x = new Use()
throw x.notFoundError()

Interested in notFoundError not being a function.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • No, you can't do that, and you shouldn't - [don't call overwritten methods in a parent constructor](https://stackoverflow.com/a/47821096/1048572)! Your only way out is making `notFoundError` a getter, or making `name` static. – Bergi Nov 19 '19 at 20:47

2 Answers2

0

One idea:

const Root = (name: string) => { 
    abstract class Root {
        name: string = name
        notFoundError = new Error(`${this.name} not found`)
    }
    return Root
}

class Use extends Root('User') {

}

const x = new Use()
throw x.notFoundError
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
0

Rather then name = 'User' or name = () => 'User' use name() { return 'User' }.

abstract class Root {
    abstract name(): string
    notFoundError = new Error(`${this.name()} not found`)

}

class Use extends Root {
    name() { return 'User' }
}

const x = new Use()
throw x.notFoundError
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424