JSDoc document object method extending other class

淺唱寂寞╮ 提交于 2019-12-11 06:37:28

问题


Document Extending jest.Matchers using JSDoc

I wrote a simple extension of jest.Matchers but I can not get the typescript type checker to recognise my extension.

I'm using plain JavaScript.

// @ts-check

const getFunctorValue = F => {
  let x
  F.fmap(v => x = v)
  return x
}


expect.extend({
  /**
  * @extends 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}`
      }
    }
  }
})

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

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

But in the line with expect(just(1)).functorToBe(just(1)), I get a red underline under functorToBe and the following error message:

[ts] Property 'functorToBe' does not exist on type 'Matchers<{ [x: string]: any; fmap: (f: any) => any; }>'. any

I got jest.Matchers from writing expect() in vscode and looked at the description.

Update: I've finally filed a bug report in the typescript repo for this: https://github.com/Microsoft/TypeScript/issues/26675


回答1:


Currently this can not be done in JSDoc.

After a bit more thought, I think the core problem is that the statement that changes the type of expect is a side-effecting function call, not a declaration. Typescript doesn’t have the ability to mutate types like that.

I think your best bet in the near term is to use a separate .d.ts file to express the type mutation as a type merge as I outlined above, although that may require some work on jest’s types if they are not amenable to merging already.

This not a satisfying solution for projects that want to be pure Javascript, however. Let’s keep this issue open to track the idea of a mutation-as-merge jsdoc tag.

Source: https://github.com/Microsoft/TypeScript/issues/26675#issuecomment-416952171

I have a follow up question on StackOverflow if anyone is interested: How to describe the interface of a simple Just functor in typescript?



来源:https://stackoverflow.com/questions/51972275/jsdoc-document-object-method-extending-other-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!