I've come across a TypeScript error while trying to implement a conditional type in a MessagesStore
object. Here is the code snippet:
type Message = { id: number; text: string };
type MessagesStore = {
queue: Array<Message>;
read: <T extends boolean>(assertiveMode?: T) => T extends true ? Message : Message | undefined;
}
const store: MessagesStore = {
queue: [],
read(assertiveMode: boolean = false) {
const message = this.queue.shift();
if (assertiveMode && message === undefined) {
throw new Error('The messages queue is empty');
}
return message;
}
}
An error is being thrown by TypeScript with the following message:
Type '<T extends boolean>(assertiveMode?: boolean) => Message | undefined' is not assignable to type '<T extends boolean>(assertiveMode?: T | undefined) => T extends true ? Message : Message | undefined'.
Type 'Message | undefined' is not assignable to type 'T extends true ? Message : Message | undefined'.
Type 'undefined' is not assignable to type 'T extends true ? Message : Message | undefined'.
I'm having trouble figuring out why this error is occurring and how to fix it.