如何在打字稿中描述一个简单的Just functor的界面?

问题描述 投票:1回答:1

我试图第一次在打字稿中写一个简单的界面,并对几乎所有事情都有疑虑。

问题很简单。如何描述这个简单的jest matcher扩展?

/**
 * @param {*} v Any value
 */
function just (v) {
  return {
    fmap: f => just(f(v))
  }
}

expect.extend({
  /** Compare the two values inside two functors with Object.is
   * @method
   * @augments jest.Matchers
   * @param {*} actual The functor you want to test.
   * @param {*} expected The functor you expect.
   */
  functorToBe(actual, expected) {
    const actualValue = getFunctorValue(actual)
    const expectedValue = getFunctorValue(expected)
    const pass = Object.is(actualValue, expectedValue)
    return {
      pass,
      message () {
        return `expected ${actualValue} of ${actual} to ${pass ? '' : 'not'} be ${expectedValue} of ${expected}`
      }
    }
  }
})

test('equational reasoning (identity)', () => {
  expect(just(1)).functorToBe(just(1))
})

我试过这个,但根本不确定泛型类型:

import { Matchers } from 'jest'

interface Functor<T> {
  (value?: any): {
    fmap: (f: value) => Functor<T>
  }
}

interface Matchers<R> {
  functorToBe(actual: Functor<T>, expected:  Functor<T>): R
}

参考:JSDoc document object method extending other class

Matchers<R>的jest类型定义的要点:

/**
 * The `expect` function is used every time you want to test a value.
 * You will rarely call `expect` by itself.
 */
interface Expect {
    /**
     * The `expect` function is used every time you want to test a value.
     * You will rarely call `expect` by itself.
     *
     * @param actual The value to apply matchers against.
     */
    <T = any>(actual: T): Matchers<T>;
    /**
     * You can use `expect.extend` to add your own matchers to Jest.
     */
    extend(obj: ExpectExtendMap): void;
    // etc.
}

嗯,这很令人困惑。 jest repo中唯一的index.d.ts是https://github.com/facebook/jest/blob/master/packages/jest-editor-support/index.d.ts,但这不是我在vscode中获得的那个,即https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jest/index.d.ts#L471

javascript typescript visual-studio-code jestjs typescript-typings
1个回答
2
投票

扩展名

你对Matchers的合并几乎是正确的,但是通过查看Definitely Typed [1]上的jest类型,我可以看到Matchers嵌套在jest命名空间内。包含此内容的Typescript手册的一部分是namespace merging

namespace jest {
    export interface Matchers<R> {
        functorToBe<T>(actual: Functor<T>, expected:  Functor<T>): R;
    }
}

当我测试这个时,我需要一个tsconfig.json来获取我的JS文件以查看声明:

{
    "compilerOptions": {
        "allowJs": true,
        "checkJs": true,
    },
    "include": [
        "test.js",
        "extensions.ts",
    ]
}

jsconfig.json几乎是一回事,但不要求你明确地添加"allowJs": true。但请注意,添加tsconfig或jsconfig将关闭自定义类型的类型的自动下载,并且您必须手动npm install @types/jest(以及您使用的库的任何其他类型)。如果您不想添加tsconfig,我可以在JS文件中手动添加引用作为第一行:

/// <reference path="./extensions.ts" />

新方法的类型

它应该是这样的:

functorToBe(expected: R): R;

这是让我感到困惑的地方。如果您对问题的这一部分有疑问,请告诉我,我会尽力提供帮助。

© www.soinside.com 2019 - 2024. All rights reserved.