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

Incompatible types due to readonly

I have a object containing a middleware property but cant get the types to work. It tells me that the two middlewares are incompatible because one of them is readonly. Is there a way to solve this? – thanks 🙂

Example

type Middleware = (...args: unknown[]) => unknown;
type Router = { middleware?: Middleware[] };

const router = {
    middleware: [() => null],
} as const satisfies Router;

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

type Router = {
    middleware?: Middleware[] | undefined;
}

Type '{ readonly middleware: readonly [() => null]; }' does not satisfy the expected type 'Router'.
  Types of property 'middleware' are incompatible.
    The type 'readonly [() => null]' is 'readonly' and cannot be assigned to the mutable type 'Middleware[]'.

>Solution :

A quick solution would be to remove the as const, which makes the object literals readonly:

const router = {
    middleware: [() => null],
} satisfies Router;

Depending on your use case: you can also change the type Router by adding the utility type Readonly:

type Router = { middleware?: Readonly<Middleware[]> };

Though you are not able to call e.g. push on router.middleware.

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