如何从父级返回子类的类型?

时间:2020-04-11 17:22:42

标签: typescript inheritance

在调用父类的 var flag = false; function listen(){ console.log("texttospeech") var synth = window.speechSynthesis; if ('speechSynthesis' in window){ if(!flag){ console.log("flag value true") flag = true; utterance = new SpeechSynthesisUtterance( document.getElementById("retrievecode").textContent); utterance.onend = function(){ console.log("reached end") flag = false; }; synth.speak(utterance); } if(synth.paused) { /* unpause/resume narration */ console.log("pauser") synth.resume(); } } else{ alert("not supported") } } 时,我很难弄清楚如何返回子类的类型,而不是父类。

在下面的示例中,代码运行没有错误,但是new this()显示为错误,因为child.hi()的类型为child,而不是Parent

Child

Typescript Playground Link

1 个答案:

答案 0 :(得分:3)

您可以通过在get方法中使用泛型来解决此问题,以便它可以正确解析类型:

static get<T>(this: new () => T) {
    return new this();
}

进行此更改后,Parent.get()和Child.get()均应按预期工作。