'Typescript: Function accepting 2 Types but property doesn't exist on one of the types

I have a function that takes 2 types.

handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) {
    e.stopPropagation();

    const newValue = this.computeValuesFromPosition(e.detail.x, e.detail.y, e.detail.variant);

    // other same code
})

the issue is that GridHandleDragEventType does not have a variant as part of the type. In those cases, I don't mind sending null but I keep getting the TS issue: Property 'variant' does not exist on type 'GridHandleDragEventType'. Is there a clean way to resolve this?



Solution 1:[1]

Here's an example that takes advantage of TypeScript's structural typing to use { detail: { x: number, y: number, variant?: string } } instead of SelectionHandleDragEventType | GridHandleDragEventType.

I'm assuming that x and y are number and variant is string - if those aren't the actual types of those properties, you should just be able to change this example:

handleDragging(e: CustomEvent<{ detail: { x: number, y: number, variant?: string } }>) {
    e.stopPropagation();

    const newValue = this.computeValuesFromPosition(e.detail.x, e.detail.y, e.detail.variant ?? null);
})

This also defaults variant to null for GridHandleDragEventType, as you mentioned, but you don't necessarily need that if computeValuesFromPosition handles the variant parameter being undefined.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Donut