打字稿从打字扩展类

时间:2018-09-05 14:20:42

标签: typescript

我有一个正在兴建的图书馆。有一个名为SearchResult的类已正确导出到我的'd.ts'文件中:

declare module my.module {
    export class SearchResult {
        id?: string;
        object_type: string;
        item?: any;
        type?: string;
    }
}

它被编译为此:

357:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var SearchResult = (function () {
    function SearchResult() {
    }
    return SearchResult;
}());
exports.SearchResult = SearchResult;
},{}]

但是当我使用引用导入此文件并尝试扩展此类时:

export class SearchResultChecked extends my.module.SearchResult {
    checked?: boolean;
}

我遇到了运行时错误:

Uncaught TypeError: Object prototype may only be an Object or null: undefined
    at setPrototypeOf (<anonymous>)
    at __extends (_prelude.js:1)

有很多类似的问题,但它们并不相同。

tsc -v:3.0.1

UPD :好像我无法extend上一次在我的库中未定义的类那样。寻找解决方案。

1 个答案:

答案 0 :(得分:0)

.d.ts文件不会发出,它们不会产生任何代码,仅存在于类型级别(概念上,在链接器级别)。

.d.ts文件编写的代码永远不会进入运行时,它只是告诉TypeScript“即使您不打算发出有关此类的JS代码,也要假定此类/枚举/存在的所有东西”。

如果您希望类在运行时中实际存在,则需要从实际的.ts文件中实际导出它,或导入一个暴露该类的库。