Unable to confirm the absence of a variable in TypeScript

I can't seem to resolve the compiler error " Object is possibly 'undefined' "

const destinationColumnIndex = (): number => {
  if (typeof result.destination === 'undefined') {
    return 0;
  }
  return boardData.findIndex(
    (column) => column.id === Number(result.destination.droppableId)
  );
};

However, TypeScript compiler still warns me that "result.destination" could be undefined.

I have attempted the following as well:

  if (result.destination === undefined) {
    return 0;
  }

and:

  if (!result.destination) {
    return 0;
  }

and:

   if (!result || typeof result.destination === 'undefined') {
    return 0;
  }

but none of them fixed the issue. I even tried restarting VS Code in case it was a bug, but the error persists.

EDIT - MORE CODE:

  const onDragEnd = async (result: DropResult) => {
if (!result.destination) {
  return;
}

const sourceColumnIndex = (): number =>
  boardData.findIndex(
    (column) => column.id === Number(result.source.droppableId)
  );

const destinationColumnIndex = (): number => {
  if (typeof result === 'undefined' || result.destination === undefined) {
    return 0;
  }
  return boardData.findIndex(
    (column) => column.id === Number(result.destination.droppableId)
  );
};

This function is part of a React component

Answer №1

It is recommended to use the following code:

  if (result === undefined || result?.destination === undefined) {
    return 0;
  }

Avoid using typeof to check for undefined.

Alternatively, you can also use:

  if (!result || result?.destination === undefined) {
    return 0;
  }

UPDATE

Consider this solution:

const onDragEnd = (result: DropResult) => {
  if (!result || !result.destination) {
    return;
  }

  const sourceColumnIndex = (): number =>
    boardData.findIndex(
      (column) => column.id === Number(result.source?.droppableId)
    );

  const destinationColumnIndex = (): number => {
    if (!result || !result.destination) {
      return 0;
    }
    return boardData.findIndex(
      (column) => column.id === Number(result.destination?.droppableId)
    );
  };
}

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

Unable to bring in @material-ui/core/styles/MuiThemeProvider

I'm currently working on a React project that utilizes Material UI React components. My goal is to import MuiThemeProvider in src/index.js with the following code snippet: import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider"; . H ...

I aim to conceal the Spinner feature within the service layer of Vue JS

I have a basic bootstrap Spinner.vue component <template> <div class="modal" v-if="start"> <div class="spinner-border text-info" role="status" style="width: 3rem; height: 3rem;" ...

Instructions on declaring a Typescript variable that will only be assigned once in the future

In the land of coding, there are two constants: const which sets a value at declaration, and let which allows for variables to be changed. But what about a special Typescript (or javascript) variable that starts as undefined, and once defined, remains fo ...

What steps can be taken to address the error in the Vue.js JSON settings within VS Code?

Greetings everyone, I am just starting out with VueJs and encountered an error in VS CODE. Please refer to the image below. Thank you for your help! ...

Interactive Range Slider for Scrolling Through Div Content

I am currently facing an issue where I want to implement a HTML range slider for controlling the horizontal scrolling of a div located below. This functionality is similar to that of a scroll bar, but it will be positioned away from the scrollable content ...

Properties cannot be accessed using the standard method in the controller; however, they function correctly when using an arrow

Currently, I am facing a challenge where traditional class methods do not allow me to access the userService. I aim to write typical class methods in my user controller like this: public async register(req: Request, res: Response, next: NextFunction): Pr ...

avoid the selection of the same options more than once

My form consists of 5 select elements with the same options. I want each option to be selected only once, so I need a code that can accomplish the following: When a user selects an option in one select element, that option should be disabled or deleted f ...

Tips on creating a script for detecting changes in the table element's rows and columns with the specified data values

I have a div-based drop-down with its value stored in TD[data-value]. I am looking to write a script that will trigger when the TD data-value changes. Here is the format of the TD: <td data-value="some-id"> <div class="dropdown">some elements& ...

The output of the Node.js crypto.pbkdf2 function may not match the result obtained from CryptoJS.PBKDF

Currently, I am utilizing PBKDF2 on both the frontend with CryptoJS and the backend with Node.js. Despite using the identical salt, algorithm, number of iterations, and password, the derived keys are turning out to be different. Below is the code snippet ...

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...

Issues with v-on:change not triggering method in nuxt.js

Despite my efforts, I can't seem to get this seemingly simple task to work. I came across a question on Stack Overflow that seemed to address the issue - how to fire an event when v-model changes Here is the component that I am working with: <tem ...

The restify.bodyParser() function does not seem to be functioning correctly, as the req object is appearing

When working with restify, I've noticed that the request object is always empty when making HTTP POST calls. Does anyone have any ideas on why this might be happening? Thanks ...

Kids in the realm of useCallback are stuck in dependency pur

My understanding of useCallback was to prevent rerendering, so I've implemented it in all my functions. However, I have a feeling that this might not be the best approach. What's even worse is that by using it everywhere, I am passing dependenci ...

Ways to showcase a JavaScript popup on an Android WebView

Can a JavaScript popup window be opened on an Android web viewer that is coded similarly to this example from Google? If so, how can this be accomplished without closing the original background page and ensuring it resembles a popup as shown in the picture ...

The error "ReferenceError: process is not defined in vue 3" is being

<script setup> import puppeteer from 'puppeteer'; const onChange = async () => { // Initializing the puppeteer library const browser = await puppeteer.launch(); // Creating a new page const page = await browser.newPage(); / ...

After restoring my Windows system, I encountered an issue with locating the typescript.js module for my Angular app development. I am currently troubleshooting the build

My PC had some issues, so I decided to restore Windows to an older restoration point. However, after doing this, I encountered an error while trying to build my Angular App: C:\Udemy\AngularDeCeroAExpertoEdicion2021\03-paisesApp>npm run ...

What is the reason for node executing both of these handlers on the server?

My node app is set up with two handlers, one for requests to the root URL and another for the slug. However, when I visit the root or slug URLs, the app crashes and I receive this error: url is pointing to root url has a slug throw err; // Rethrow non-MySQ ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

There appears to be an issue with Three.js as it is indicating that the node.apply

I am currently attempting to import a .fbx file using the FBXLoader from three.js with the following code block: var fbxLoader = new THREE.FBXLoader(); fbxLoader.load('assets/item2.fbx', function (object){ object.position.y = -100; scene.add(obj ...

Chart.js encounters difficulties displaying the chart due to the data in reactjs

My goal is to utilize chartjs-2 to showcase a bar graph with data. Below is the code I've implemented: import React from "react"; import { Bar, Line, Pie } from "react-chartjs-2"; export default class App extends React.Component { constructor(pro ...