I've been diving into the book Programming TypeScript, and I'm currently stuck on understanding the concept of refinement as shown in this example:
type UserTextEvent = { value: string; target: HTMLInputElement };
type UserMouseEvent = { value: [number, number]; target: HTMLElement };
type UserEvent = UserTextEvent | UserMouseEvent;
function handle(event: UserEvent) {
if (typeof event.value === "string") {
event.value; // string
event.target; // HTMLInputElement | HTMLElement (1)
// ...
return;
}
event.value; // [number, number]
event.target; // HTMLInputElement | HTMLElement (2)
}
In my interpretation, the type of event.target should be HTMLInputElement for (1) and HTMLElement for (2). I believe that if the type of event.value is specific, then the type of event.target should also be specific. However, it appears to be HTMLInputElement | HTMLElement instead. Can someone provide a clearer explanation than what's given in the book? Your help is much appreciated.