在 Typescript 中定义类之外,您如何定义成员函数?
引用 c++ 中的一个例子:
class A
{
void runThis();
//Member variables and constructors here
}
A::runThis()
{
//code goes here
}
你如何在打字稿中实现相同的目标?通过在谷歌中搜索,我找到了类似的东西:
class A
{
runThis: () => void;
}
A.prototype.runThis = function(){
//Anonymous function code goes here
}
但是,我还没有找到语法,对具有返回类型(例如数字或字符串(的函数执行相同的操作。
如何实现这一点?
您绝对可以使用相同的语法来添加具有返回类型的函数:
class A {
add: (a: number, b: number) => number;
}
A.prototype.add = (a: number, b: number): number => {
return a + b;
}
在 TypeScript 中,您可以使用静态方法来解决您的问题。
样本:
export class Person {
private static birthday : Date;
public static getBirthDay() : Date {
return this.birthday;
}
}
Person.getBirthDay();