我有一个基类 A 和一个覆盖 A 的 fetch 方法的扩展类 B。 但是,当我调用 B.fetch() 时,它会记录“基类”。为什么不调用B中定义的方法定义?
class A {
protected apiPath: string = ''
static async fetch (id = null, Model = this, apiPath = this.apiPath): Promise<any> {
console.log('basefetch')
let url = apiPath
if(id) url += '/' + id
let { data } = await axios.get(url)
let item: any = new Model(data)
return item
}
}
class B extends A {
static async fetch(id = null, Model = this, apiPath = this.apiPath): Promise<Data> {
console.log('childfetch')
let {data} = await axios.get(apiPath)
if (typeof data.challenge.participating == 'undefined') {
data.challenge.participating = null
}
if (typeof data.challenge.progress == 'undefined') {
data.challenge.progress = null
}
return new Model(data)
}
class SomeOtherModule {
async doSomething() {
let b: B = await B.fetch()
}
}
最佳答案
嗯,方法签名是不同的。在 A 中,您返回 Promise<any>
但在 B 中你返回 Promise<Data>
.
可以在this snippet中看到您正在尝试做的事情肯定会奏效:
class A {
static fetch (): string {
return 'basefetch';
}
}
class B extends A {
static fetch(): any {
return 'childfetch';
}
}
let aVal: string = A.fetch();
console.log(`aVal: ${aVal}`);
let bVal: string = B.fetch();
console.log(`bVal: ${bVal}`);
关于javascript - typescript 方法覆盖不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47376027/