【问题标题】:Typescript: Declare functions without implementing them打字稿:声明函数而不实现它们
【发布时间】:2017-06-21 17:17:41
【问题描述】:

是否可以声明一个类具有某些功能而不实现它们?

我需要这个,因为我创建了一个类,然后将其传递给一个 js 框架,该框架添加了几个函数。我也希望能够调用这些函数,而无需重新实现它们、重定向或强制转换或其他任何方式。

例子:

//example class
class AppComponent {
   constructor() {}
}

//create class
var comp: AppComponent = new AppComponent();

//hand over to framework
fw.define("Component", comp);

//now I want to be able to call the added functions such as:
comp.setModel(/*some model*/);

【问题讨论】:

  • 我猜您可以使用这些方法获得interface,并且可以键入对fw.define 的调用以返回该接口的对象(只需再次返回comp,但您可以将其分配给类型化的第二个变量)。或者只是将您的comp 投射到该界面(可能通过any)。
  • 不幸的是define 没有返回任何东西。这就是为什么我将它转换为在 d.ts 文件中定义的sap.ui.core.mvc.Controller(framework SAPUI5)。最简单的方法是将两者结合起来
  • declare that a class has certain functions without implementing them:这就是 abstract classes 的用途
  • @BrunoGrieder 的问题是它们不能被实例化,框架必须创建它的子类。最好只定义一个带有框架可以设置的一些可选属性的接口。
  • 但是使用抽象类我必须稍后在派生类的某个地方实现这些函数。我根本不想实现这些功能,因为它们已经在 javascript 框架中实现了

标签: class typescript sapui5


【解决方案1】:

你可以声明函数而不实现它。

//example class
class AppComponent {
    constructor() { }
    setModel: () => void;
}

//create class
var comp: AppComponent = new AppComponent();

//hand over to framework
fw.define("Component", comp);

//now I want to be able to call the added functions such as:
comp.setModel(/*some model*/);

【讨论】:

  • 这就是我需要的,谢谢。但是有没有没有箭头功能的方法?
  • 这是 TypeScript 声明函数的方式。
  • 但它声明它为箭头函数,所以如果我想在派生类中覆盖它,我还必须使用箭头函数。 (这会导致框架出现问题,因为它使用另一个 this 而不是类实例 this 调用函数。在箭头函数中 this 绑定到类实例)
  • 声明使用箭头,但赋值时不必使用。 comp.setModel = function() {};
  • 函数有返回类型时如何声明? @罗德里斯
猜你喜欢
  • 2019-12-14
  • 2019-03-26
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多