问题
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