【问题标题】:TypeScript error when createBrowserHistory's push method may not existcreateBrowserHistory 的 push 方法可能不存在时出现 TypeScript 错误
【发布时间】:2020-11-16 18:37:36
【问题描述】:

如果我检查历史对象,那么我的代码没有错误:

   const handleClick = () => {
     if (history) {
       history.push('/');
     }
   };

我认为这将是相同的,但它会产生一个 TypeScript 错误:

  const handleClick = () => {
    // if (history) {
    history?.push('/');
    // }
  };

错误 TS2339: 属性 'push' 不存在于类型 '"" |历史'。 类型 '""' 上不存在属性 'push'。

27 历史?.push('/');

它们实际上不是一回事吗?

我要导入的历史是这样的:

import { createBrowserHistory } from 'history';
export default process.env.BROWSER && createBrowserHistory();

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您收到错误是因为 ? 运算符实际上不会阻止您运行该函数,如果未设置 history 可能会失败,这就是 TypeScript 抛出错误的原因。当这段代码编译时,它可能仍然会失败,TypeScript 正试图阻止这种失败。

    ? 运算符只会阻止您“尝试访问 null 或未定义的属性”,但不会阻止函数调用。

    就像你提到的那样

     const handleClick = () => {
         if (history) {
           history.push('/');
         }
       };
    

    或者这个

     const handleClick = () => {
         history && history.push('/')
      };
    

    这是解决这个问题的正确方法

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多