Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters.

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

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

    // other same code
})

The problem arises when GridHandleDragEventType does not include a property called variant within its type. In such cases, I'm okay with passing null, but I keep encountering the TypeScript issue:

Property 'variant' does not exist on type 'GridHandleDragEventType'.
Is there a neat solution to this issue?

Answer №1

When deciding between two options, one possibility is to opt for the Partial approach, while the other option involves using the variant property.

e: CustomEvent<SelectionHandleDragEventType | Partial<GridHandleDragEventType>>

Alternatively,

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

Answer №2

Check out this demonstration that utilizes TypeScript's structural typing by using

{ detail: { x: number, y: number, variant?: string } }
in place of
SelectionHandleDragEventType | GridHandleDragEventType
.

In this scenario, I assume x and y are both of type number, while variant is of type string. If these types differ from the actual properties, feel free to modify the example accordingly:

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);
})

In this code snippet, variant is also set to null for cases involving GridHandleDragEventType. However, this may not be necessary if computeValuesFromPosition can handle scenarios where the variant parameter is undefined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

Ember Component Incorporating Keyboard Input

I recently developed an ember component that features a rectangular block in a green canvas. Everything is working smoothly so far. However, I am facing some challenges with implementing keyboard input commands (A S D W) to navigate the rectangle within t ...

Tips for rearranging sibling divs while maintaining the order of their child elements

Is there a way to shuffle the order of div classes shuffledv, while maintaining the same order of id's each time the page is refreshed? <div class="shuffledv"> <div id="2"></div> <div id="3"></div> <div id="1">< ...

The variable req.body.username is not defined in the context of JavaScript

I am completely new to JS, Angular.js and node.js. I am currently working on a login-register project but facing a minor issue. Below is my code: login.ctrl.js: var app = angular.module('login-register', []); app.factory('UserLog', ...

Selecting the child checkbox within the parent div using ng-click

Is there a way to trigger the click event of a parent div on its child checkbox in AngularJS? The Checkbox will have the attribute hidden, necessitating the parent div to act as the clickable element. Sample HTML: <body ng-app="checkboxApp"> ...

Are we on the correct path for breaking down code using react JS?

As I work on creating reusable table components, each column comes with its own set of functionalities, which results in dealing with numerous components. To streamline the process, I have been separating every component piece into individual files and ex ...

Having trouble getting unique input values to pass through ajax

For the past couple of weeks, I've been searching for a solution to my issue. The problem arises in my PHP foreach loop where I have div tags representing rows of data fetched from the database. Each div row contains HTML input elements and a button t ...

Improving the management of user input in Lit components

I am seeking a more efficient method to manage all inputs within my lit component while minimizing the code usage. I am also employing Typescript in this process, utilizing @change=${this.handleInput} for all input fields. Below is an example of how the ha ...

Can a javascript code for "Infinite Scroll" be created to manage the back button?

Head over to this website: Experiment with the infinite scroll feature. You may notice that when you click a link and then press "back", there are some glitches. Therefore, I am considering developing my own version of an Infinite Scroll functionality. ...

Using React TypeScript to trigger a function upon route changes with react-router-dom

I am trying to use the useEffect hook to console log every time the location changes in my project. However, when I try to compile, I receive an error in the terminal saying Unexpected use of 'location' no-restricted-globals. I would like to fin ...

Retrieve no data from Firebase using Cloud Functions

I am a beginner with Google Firebase and Cloud Functions, and I recently attempted a basic "hello world" program: Established a connection to Cloud Firestore [beta], which contains over 100,000 records. Retrieved the top record from the database. Below ...

Utilizing Semantic-UI-React and Webpack to Set the Path for an Image

I am currently developing a ReactJS application using webpack. This basic example is supposed to display an <img> tag with a specified URL in the src attribute. How can I bundle the image resource using webpack and process it with the appropriate l ...

The export of a corrupted "OffscreenCanvas" is prohibited

Currently, I am implementing a process where an ImageBitmap is passed into a web worker in order to render it on a canvas. Subsequently, a URL is generated for loading into THREE.js on the main thread. Within the main thread this.canvas = this.canvasEl. ...

Combine a constant interface with a generic function to create a unique generic interface

When dealing with legacy code that utilizes a const in the following pattern: const fnUsedInSetPrototypeOf = { equalityComparer<T>(a: T, b: T) { return a === b }, otherFn<T> (this: T) { /*...*/ }, // ... other things, all along the ...

Redirecting JavaScript form to search engine

I am struggling with creating a form that enables a user to input text and then directs them to a specified search engine with the input as the query. I am encountering difficulties in getting the JavaScript to properly redirect. An interesting observatio ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

The differences between using the opacity attribute in HTML and the opacity property

There are two distinct methods for adjusting opacity in HTML: <div opacity="0.5"></div> and <div style="opacity: 0.5;"></div> I am familiar with setting these values in JavaScript as well: div.setAttribute("opacity", 0.5); and ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Version 10.0 of sails is having trouble with an undefined 'schema' when using mysql

i'm currently experimenting with sails js version 0.10.0 using the sails-mysql adapter 0.10.6 I have set up two models: Customer.js module.exports = { connection: 'someMysqlServer', attributes: { name: { type: 'string& ...