我有一个打字稿类
class BlockJsonBig {
private m_simpleStorage:simplestoragejs.SimpleStorage;
...
}
并希望扩展(子类)常规非TS函数,如:
var BlockJsonSmall = Block.extend({...})
所以基本上我希望BlockJsonBig扩展BlockJsonSmall但BlockJsonSmall是纯JS(不是TS)
有可能吗?
tx用于阅读,
肖恩。
答案 0 :(得分:1)
有可能吗?
是。和惯用的
class BlockJsonSmall extends BlockJsonBig {
}
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function BlockJsonSmall {}
__extends(BlockJsonSmall, BlockJsonBig);
此处涵盖_extends
功能:https://basarat.gitbooks.io/typescript/content/docs/classes-emit.html
答案 1 :(得分:0)
很好地找到了解决方案,但这不是那么微不足道......
首先,您要创建一个从模块挂起的抽象类:
///<reference path="../jquery/jquery.d.ts" />
///<reference path="../backbone/backbone.d.ts" />
declare module TSLiteModules {
class Block extends Backbone.View<Backbone.Model> {
protected m_blockProperty:any;
protected m_block_id:any;
protected m_blockType:any;
protected _initSubPanel(i_panel:any);
protected getBlockData():any;
protected _initSubPanel(i_panel:string):void;
protected _getBlockPlayerData():any;
protected _loadBlockSpecificProps():any;
protected _viewSubPanel(i_panel:string):any;
protected _setBlockPlayerData(domPlayerData:any, notification:string):any;
public sayHello();
}
}
接下来你要扩展你的抽象类(在我的情况下,我使用require AMD):
///<reference path="../../typings/lite/app_references.d.ts" />
define(['jquery', 'Block'], function ($, Block) {
TSLiteModules['Block'] = Block;
class BlockJson extends TSLiteModules.Block {
private m_options;
private m_actions:Object;
private m_jsonEventTable:any;
private m_jsonRowEventChangedHandler:Function;
private m_addNewEvent:Function;
private m_pathChange:Function;
private m_intervalInput:Function;
private m_playVideoCompletion:Function;
private m_removeEvent:Function;
private m_onDropDownEventActionGoToHandler:Function;
private m_onDropDownEventActionHandler:Function;
private m_selected:any;
constructor(options?:any) {
this.m_options = options;
super();
}
...
和真正的魔力,是因为TypeScript在你的全局变量周围创建了一个闭包(即:这就是为什么我们将抽象类放在一个模块中,所以路径将与下面的声明相同)
window.TSLiteModules = {};
所以再次解释一下,首先要创建window.TSLiteModules = {};这是全局的,你继续创建一个带有抽象类的模块,这将导致TS创建成员,如下所示:
define(['jquery', 'Block'], function ($, Block) {
TSLiteModules['Block'] = Block;
var BlockJson = (function (_super) {
__extends(BlockJson, _super);
...
return BlockJson;
})(TSLiteModules.Block);
return BlockJson;
现在您可以使用TypeScript扩展vanilla JavaScript,获得完整的IntelliSence并且不会收到来自TS Transpiller的投诉,同时可以完全访问受保护的成员/方法......
希望这有助于某人...
您可以在以下网址找到代码:
https://github.com/born2net/signagestudio_web-lite/blob/master/_controllers/_blocks/BlockJson.ts
https://github.com/born2net/signagestudio_web-lite/blob/master/StudioLite.js
https://github.com/born2net/signagestudio_web-lite/tree/master/typings/lite