函数在接口和类中重载 - 如何? [英] Functions Overloading in interface and classes - how to?
本文介绍了函数在接口和类中重载 - 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个界面:
interface IPoint {
getDist(): string;
getDist(x: number): any;
}
我需要一个班来实现它但是我无法做到在类中实现getDist()方法
的语法..
and I need a class to implement it but I can't get the right syntax to implement the getDist() method in the class..
class Point implements IPoint {
// Constructor
constructor (public x: number, public y: number) { }
pointMethod() { }
getDist() {
Math.sqrt(this.x * this.x + this.y * this.y);
}
// Static member
static origin = new Point(0, 0);
}
它说:
类'Point'声明接口'IPoint'但不实现它:
类型'Point'和'IPoint'的属性'getDist'的类型是
不兼容:调用类型'()=> void'和'{():string的签名;
(x:数字):任意; }'不兼容
Class 'Point' declares interface 'IPoint' but does not implement it: Types of property 'getDist' of types 'Point' and 'IPoint' are incompatible:Call signatures of types '() => void' and '{ (): string; (x: number): any; }' are incompatible
这样做的正确方法是什么?
What's the proper way to do this?
谢谢
推荐答案
当您在类中声明该函数时,需要使用重载来装饰它:
When you declare the function in the class you need to decorate it with the overloads:
getDist(): string;
getDist(x: number): any;
getDist(x?: number): any {
// your code
}
这篇关于函数在接口和类中重载 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文