Home > database >  why typeof cannot narrow the union type
why typeof cannot narrow the union type

Time:12-15

When using typeof to narrow the union type, it surprises me that on the premise that under the if condition we get the particular type of field value but cannot infer the type of field targetcorrectly. Why cannot infer that the type of target is HTMLInputElement when know the value is a string?

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 but not HTMLInputElement, why ?
                 //
    return
  }


}

CodePudding user response:

The type of narrowing you're looking for I believe falls under the category discriminated unions.

  • Related