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
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[]'.
CodePudding user response:
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
.