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 ๐Ÿ™‚


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

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


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.

Leave a Reply Cancel reply