简体   繁体   English

无法检查变量是否在 typescript 中未定义

[英]can't check if variable is undefined in typescript

I'm trying to solve compiler error " Object is possibly 'undefined' "我正在尝试解决编译器错误“Object 可能是‘未定义’”

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

but typescript compiler still tells me that "result.destination" may be undefined.但 typescript 编译器仍然告诉我“result.destination”可能未定义。

I have tried also:我也试过:

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

and:和:

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

and:和:

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

and nothing works.没有任何效果。 Even thought it may be some bug so i restarted VS Code but there are still the same error.甚至认为这可能是一些错误,所以我重新启动了 VS Code,但仍然存在相同的错误。

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

it's function inside of react component它是反应组件内部的 function

You should just do:你应该这样做:

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

Checking typeof is not a good way to check for undefined.检查typeof不是检查未定义的好方法。

or或者

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

UPDATE更新

try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM