【问题标题】:Overwrite / extend typescript class expressions覆盖/扩展打字稿类表达式
【发布时间】:2019-04-17 13:53:59
【问题描述】:

我的公司已经为该软件开发了自己的测试框架,因为在我们开发的软件的上下文中无法使用开源框架。

无论如何,我编写了 Typescript 定义文件来改进 VS Code 的代码完成,但我无法使其适用于以下设置:

以下类用于定义单元测试。它提供了一些功能,例如为断言。主要问题是 util-namespace。您可以传递一个实际上是单元测试的函数。请注意,该函数的 this-object 指向单元测试类,以便传递的函数可以使用单元测试的函数(在内部,传递的函数将通过“unitTest.call(this)”调用来设置函数的this对象到单元测试实例)

class UnitTest {
    constructor(unitTest: (this: UnitTest) => void);
    .
    .
    .
    util = Util; // Referes to the Util-Class (it's a class because its the only possibility in typescript for nesting 

Util 类提供了一些对编写测试有用的通用函数

class Util {
    static createFile(filePath: string): File;
    .
    .
    .
}

如果你像这样声明一个单元测试,一切正常:

var unitTest = new UnitTest(function() {
     this.util.createFile("..."); // VS-Code provides code completion for that functions of the unit-test-namespace
});

问题是,util-class(用于 代码封装)可以在每个项目中扩展。您可以按照特定名称模式定义脚本,并且测试框架会动态加载该脚本并在 util 命名空间中提供该函数,例如“test.util.myProject.js”

module.exports = {
    myCustomUtilFunction = function () { ... }
};

只需提供脚本,您就可以在单元测试中使用该功能:

var unitTest = new UnitTest(function() {
 this.util.myCustomUtilFunction();
});

但我无法用打字稿定义文件来涵盖这一点。 VS-Code 不会为自定义 util 函数提供任何代码完成,因为它在测试框架的 typescript 定义中缺失。我尝试如下扩展 Util 类,但 VS-Code 不在乎:

class Util {
    static myCustomUtilFunction(): void;
}

知道如何解决这个问题吗?


为了更容易理解,这里是完整的设置
testframework.d.ts

class UnitTest {
    constructor(unitTest: (this: UnitTest) => 

    util = Util;
}

class Util {
    static createFile(filePath: string): File;
}

myExtendedUtilNamespace.d.ts

class Util {
    static myCustomUtilFunction(): void;
}

unitTests.js

var unitTest = new UnitTest(function() {
    this.util.createFile("..."); // works
    this.util.myCustomUtilFunction(); // does not work
});

【问题讨论】:

    标签: typescript class inner-classes extend overwrite


    【解决方案1】:

    在我看来,Util 类从未被实例化过。如果这是正确的,它不应该是一个类。 namespace 在这种情况下更合适。命名空间也可以在声明文件之间合并。

    // testframework.d.ts
    class UnitTest {
        constructor(unitTest: (this: UnitTest) => void);
    
        util = Util;
    }
    
    declare namespace Util {
        export function createFile(filePath: string): File;
    }
    
    // myExtendedUtilNamespace.d.ts
    declare namespace Util {
      export function myCustomUtilFunction(): void;
    }
    

    请参阅关于命名空间的 TypeScript 手册: https://www.typescriptlang.org/docs/handbook/namespaces.html

    【讨论】:

    • ups .. stackoverflow 的电子邮件被推送到垃圾邮件文件夹中。你是对的,没有 util 类的实例。我将在下周尝试并提供反馈
    • 好的,如果我将类更改为命名空间,它会按预期工作。谢谢!
    猜你喜欢
    • 2019-01-06
    • 1970-01-01
    • 2017-10-02
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    相关资源
    最近更新 更多