【问题标题】:can't check if variable is undefined in typescript无法检查变量是否在打字稿中未定义
【发布时间】:2021-03-31 23:19:22
【问题描述】:

我正在尝试解决编译器错误“对象可能是'未定义'”

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

但是打字稿编译器仍然告诉我“result.destination”可能是未定义的。

我也试过了:

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

和:

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

和:

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

没有任何效果。甚至认为这可能是一些错误,所以我重新启动了 VS 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)
  );
};

react 组件内部的函数

【问题讨论】:

  • 它说的是哪个对象?
  • 它强调'result.destiantion'
  • if(result?.destination === 'undefined')
  • 它说“此条件将始终返回 'false',因为类型 'DraggableLocation | undefined' 和 'string' 没有重叠。”当我做 if(typeof result?.destination === 'undefined') 和以前一样的错误时。

标签: javascript typescript


【解决方案1】:

你应该这样做:

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

检查typeof 不是检查未定义的好方法。

或

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

更新

试试这个:

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

【讨论】:

  • 很好奇,为什么使用typeof 不适合检查undefined?
  • 不幸的是,这些都不适合我。还是有错误。
  • 尝试将第一个更改为result?.destination。我编辑了我的答案
  • 因为检查值本身基本上是一样的,但更直接。
  • 变量result在哪里声明?你能发布完整的东西吗?
猜你喜欢
  • 2019-11-16
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2019-02-01
  • 2021-06-11
  • 2015-05-24
  • 2021-01-19
相关资源
最近更新 更多