我正在尝试学习一些TypeScript知识,并且我刚刚意识到派生类中重写方法的实现不同于其他静态类型化语言(例如Java)。
例如,我意识到我可以在TS中做到这一点:
class Base {
constructor(greet: string){
console.log('base', greet);
}
getExample(arg1: unknown): unknown{
console.log('base getExample', arg1);
return ''
}
}
class Derived extends Base{
constructor(){
super('Hello');
}
getExample(arg1: string): string{
console.log('derived getExample', arg1);
return 'something'
}
getExample2(arg1: string): string{
console.log('derived getExample2', arg1);
return '2'
}
}
const doj: Base = new Derived();
doj.getExample(123); // derived getExample 123
doj.getExample('123'); // derived getExample “123”
(doj as Derived).getExample2('123');
我想知道为什么派生类中的 getExample 不重载(参数类型和返回类型与Base类中的 getExample 不同)?
我在TS手册中找不到方法重载的规则,希望能在这里获得帮助。非常感谢。