将字符串传递给抽象类的构造函数

时间:2019-11-19 20:40:08

标签: typescript class abstract-class es6-class

我正在寻找一种在类中设置名称字符串并在构造函数级别的抽象类中使用它的方法,这意味着不在函数内使用。我无法打开构造函数,因为我正在使用typedi

Here's the playground link.

  

未捕获的TypeError:this.name不是函数

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

我不是在寻找这个东西

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()

notFoundError不是函数感兴趣。

2 个答案:

答案 0 :(得分:0)

一个主意:

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

答案 1 :(得分:0)

使用name = 'User'代替name = () => 'User'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