Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript type incompatibility (Argument of type number not assignable to 1 | 2 | 3 | 4)?

This Options class has a factory function that returns a custom instance of the class. This is it:

export class Options {
  quadrant?: 1 | 2 | 3 | 4 = 1;
  static factory(options: Partial<Options>): Options {
    const defaults: Options = new Options();
    return {
      ...defaults,
      ...options,
    };
  }
}

And I’m trying to pass in an factory function argument that modifies the quadrant like this:

export const defaults = {
  quadrant: 2,
};

const responsive: Options = Options.factory({
  ...defaults,
});

And it produces this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Argument of type '{ quadrant: number; }' is not assignable to parameter of type 'Partial<Options>'.
  Types of property 'quadrant' are incompatible.
    Type 'number' is not assignable to type '1 | 2 | 3 | 4'.(2345)

Is there way to fix this?

>Solution :

If you hover over the defaults, you will see that the inferred type is number – you’ll see something like this:

const defaults: { quadrant: number };

There are 2 ways to deal with this issue. You can either cast the defaults as const, meaning the type will be as follows:

export const defaults = { quadrant: 2 } as const;
// the type is "defaults: { readonly quadrant: 2 }"

The other way you can achieve what you want is actually type the defaults object so it’s not inferred:

export const defaults = <Options>{ quadrant: 2 };
// or
export const defaults: Options = { quadrant: 2 };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading