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

Time:02-26

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?

CodePudding user response:

You can try one of the either way, I would go with the Partial one but as you need the variant property you can use the 2nd.

e: CustomEvent<SelectionHandleDragEventType | Partial<GridHandleDragEventType>>

or

e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType & {variant: null}>

CodePudding user response:

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.

  • Related