Skip to content

[TypeScript] Can't match a request body if it contains a readonly array #2174

@laurence-myers

Description

@laurence-myers

What is the expected behavior?

Can pass an object containing a readonly array as a request matching object.

What is the actual behavior?

TSC compares against each type in the union DataMatcher, fails to match on the type DataMatcherArray, reaches the last type in the union - DataMatcherMap - and raises a confusing error message, masking the root cause.

error TS2345: Argument of type 'Foo' is not assignable to parameter of type 'string | RegExp | Buffer | DataMatcherArray | DataMatcherMap | ((body: any) => boolean) | undefined'.
  Type 'Foo' is not assignable to type 'DataMatcherMap'.
    Index signature is missing in type 'Foo'.

Possible solution

Change the definition of DataMatcherArray, from this:

interface DataMatcherArray extends Array<DataMatcher> {}

To this:

interface DataMatcherArray extends ReadonlyArray<DataMatcher> {}

How to reproduce the issue

interface Foo {
  bar: readonly string[];
}

const requestToMatch: Foo = {
  bar: ['baz']
};

nock(someHost)
  .post(someUrl, requestToMatch) // <-- TSC error occurs here
  .reply(201);

Does the bug have a test case?

No, it affects the type definitions.

Versions

Software Version(s)
Nock 13.0.7
Node v14.15.4
TypeScript 4.1.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions