Description
I have two interfaces (MiddlewareResponse
& MiddlewareResponseNext
) which should be the only two possible return type for both a function or an asynchronous function (CallbackOrPromiseCallback
).
But in the example below, TypeScript does not complain when using a wrong return type for the function.
Question
What should I do in TypeScript to make sure that the union type as a return type of a function or an asynchronous function is correctly typed, and prevent possible typing mistakes?
Source-code
type CallbackOrPromiseCallback<Type> = (() => Promise<Type>) | (() => Type);
interface MiddlewareResponseNext {
next: true;
}
interface MiddlewareResponse {
next: false,
headers: Record<string, string>;
status: number;
body: string;
}
interface Middleware {
response: CallbackOrPromiseCallback<MiddlewareResponse | MiddlewareResponseNext>;
}
interface Server {
middlewares: Array<Middleware>;
}
const server = {
middlewares: [
{
response: () => ({
next: true,
status: 200 // Should not accept anymore properties
})
},
{
response: () => ({
next: true, // Should be forced to false
headers: {},
status: 500,
body: "Error"
})
}
]
};