Skip to content

Weird type error with nested objects with index type #23

Description

@G-Rath

I'm not too sure why this error is happening, and was hoping you could shed some light on if this is a bug with this library, or something I just have to work around:

interface Mx {
  data: {
    prop: string | null;

    [K: string]: unknown;
  };
}

const f = makeFactory<Mx>({ data: { prop: null } });

const f1 = f.build();
const f2 = f.build({
  ...f1,
  data: {
    ...f1.data,
    v: 'hello world'
  }
});

The above code gives the following error:

TS2345: Argument of type '{ data: { v: string; prop: string | null; }; }' is not assignable to parameter of type 'RecPartial<Mx>'.
  Types of property 'data' are incompatible.
    Type '{ v: string; prop: string | null; }' is not assignable to type 'RecPartial<{ [K: string]: unknown; prop: string | null; }>'.
      Property 'prop' is incompatible with index signature.
        Type 'string | null' is not assignable to type 'RecPartial<unknown> | undefined'.
          Type 'null' is not assignable to type 'RecPartial<unknown> | undefined'.

If I change the index type to be any, v becomes the problem:

TS2345: Argument of type '{ data: { v: string; prop: string | null; }; }' is not assignable to parameter of type 'RecPartial<Mx>'.
  Types of property 'data' are incompatible.
    Type '{ v: string; prop: string | null; }' is not assignable to type 'RecPartial<{ [K: string]: any; prop: string | null; }>'.
      Property 'v' is incompatible with index signature.
        Type 'string' is not assignable to type 'RecPartial<any> | undefined'.

The error goes away when I do the following:

  • Remove the ...f1.data
  • Add prop: <string> (but not prop: null)
  • Add prop: undefined
  • Change the signature of prop to string | undefined

None of these work if I use any instead of unknown, nor if I use a subfactory:

const f2 = f.build({
  ...f1,
  data: makeFactory<Mx['data']>({ prop: null }).build({
    ...f1.data,
    v: 'string'
  })
});

Overall, I'm pretty confused by this 😂
Let me know if there's anything else I can provide!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions