【问题标题】:TypeScript interfaces for $.extend prototype inheritance用于 $.extend 原型继承的 TypeScript 接口
【发布时间】:2018-07-09 10:09:27
【问题描述】:

我正在开发其他一些使用 vanilla JS 构建的项目。当我现在继续工作时,我想使用 TypeScript,但立即遇到了一个问题:我不能使用“正常”的原型继承,因为以前的所有者 Object.freezed 是基础对象。然而,他自己通过使用$.extend(SubObject.prototype, BaseObject.prototype)(其中$ 是jQuery)继承了这些对象。

例子:

function BaseObject() {}

BaseObject.prototype.foo = function () { console.log("foo"); };
Object.freeze(BaseObject);

function SubObject() {}

// Now he either uses this pattern:
SubObject.prototype = $.extend({}, BaseObject);

// Or this:
$.extend(SubObject.prototype, BaseObject.prototype);

由于像class extends BaseObject {} 这样的TypeScript 代码库继承不起作用,我考虑保持他的模式。但这需要我用构造函数和原型定义对象,但我失败了。

有人知道解决办法吗?

【问题讨论】:

    标签: javascript jquery typescript interface prototype


    【解决方案1】:

    当然你可以在这里添加类型:

    type BaseObject = { foo: () => void; };
    function BaseObject(): { new() => BaseObject } {}
    
     BaseObject.prototype.foo = function () { console.log("foo"); };
    

    【讨论】:

    • 您好乔纳斯,感谢您的快速回复。这对我来说效果很好......但对于const bar = new SubObject(),bar 的类型为any。有没有办法在没有const bar: SubObject = new SubObject() 的情况下推断SubObject 的类型?
    • @florian read on here
    • 有点老套,但这是可行的!现在...感谢您的参考:)
    猜你喜欢
    • 2012-02-19
    • 2021-08-17
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2011-02-17
    • 2021-07-18
    • 2020-01-29
    相关资源
    最近更新 更多