【问题标题】:Jasmine custom matcher type definitionJasmine 自定义匹配器类型定义
【发布时间】:2018-04-10 10:25:39
【问题描述】:

我正在尝试将打字稿定义添加到茉莉花匹配器library。

我能够为泛型类型 T 添加匹配器,但现在我只想将匹配器添加到 DOM 元素。

深入研究 jasmine 类型定义代码,我发现了与 ArrayLike 类似的方法(对于 expect 重载,请参见 here,对于 ArrayLikeMatchers,请参见 here)。

所以我创建了一个类似的。

// Overload the expect
declare function expect<T extends HTMLElement>(actual: T): jasmine.DOMMatchers<T>;

declare namespace jasmine {
    // Augment the standard matchers. This WORKS!
    interface Matchers<T> {
        toBeExtensible(): boolean;
        toBeFrozen(): boolean;
        toBeSealed(): boolean;
        // ... other
    }
    // The matchers for DOM elements. This is NOT working!
    interface DOMMatchers<T> extends Matchers<T> {
        toBeChecked(): boolean;
        toBeDisabled(): boolean;
    }
}

但是,不工作:(

给定以下代码:

const div = document.createElement("div");
expect(div).toBeChecked();

类型检查器给了我错误:

[js] 类型“Matchers”上不存在属性“toBeChecked”。


唯一的解决方案似乎是在核心 jasmine 库中添加expect 重载之前通用expect(在ArrayLike 重载here 之后)。

但是...这是不可行的:)

关于如何正确实施有效解决方案的任何提示?

【问题讨论】:

    标签: typescript jasmine matcher type-definition jasmine-matchers


    【解决方案1】:

    问题在于 Typescript 按声明顺序选择重载,而非常通用的 declare function expect&lt;T&gt;(actual: T): jasmine.Matchers&lt;T&gt;; 将出现在您的重载之前。您也许可以使用 /// 引用找到一些神奇的排序,但我无法让它工作,而且它会非常脆弱。

    更好的方法是在Matchers&lt;T&gt; 上添加您的额外功能,但限制this 派生自Matchers&lt;HTMLElement&gt;

    declare namespace jasmine {
        interface Matchers<T> {
            toBeExtensible(): boolean;
            toBeFrozen(): boolean;
            toBeSealed(): boolean;
    
            // this must be derived from Matchers<HTMLElement>
            toBeDisabled(this: Matchers<HTMLElement>): boolean;
            // or make it generic, with T extending HTMLElement if you really need the actual type for some reason 
            toBeChecked<T extends HTMLElement>(this: Matchers<HTMLElement>): boolean; 
        }
    }
    
    // usage
    const div = document.createElement("div");
    expect(div).toBeChecked(); // ok
    expect(10).toBeChecked() // error
    

    【讨论】:

    • 感谢@Titian,这就像一个魅力!最后我使用了:toBeChecked&lt;T extends HTMLElement&gt;( this: Matchers&lt;T&gt;): boolean;
    猜你喜欢
    • 2017-10-02
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多