【问题标题】:Spread with optional chaining failing with TypeScript and Webpack使用 TypeScript 和 Webpack 的可选链接失败的传播
【发布时间】:2021-03-31 23:39:22
【问题描述】:

我有一个与 webpack 捆绑的 TypeScript 应用程序。

我正在使用扩展运算符:

const payload = {
  ...originalList,
  byKey: {
    [listId]: {
      ...originalList?.byKey[listId],
      members: [
        ...originalList?.byKey[listId]?.members, // <== members may be undefined
        {
          id: data?.attributes?.id,
        },
      ],
    },
  },
};

members 未定义时,我得到一个错误:

TypeError: can't access property Symbol.iterator of undefined

但这只会发生在 Firefox 上;例如,在 Chrome 上,它通过了。 可能与我的 webpack 构建或 tsconfig 有关吗?

这是 tsconfig:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/",
    "jsx": "react",
    "allowJs": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "ES6",
    "lib": ["ES6", "dom", "esnext"],
    "resolveJsonModule": true,
    "esModuleInterop": true,
  },
  "include": ["./src/**/*", "./*"]
}

这是我的 webpack

const webpackClientDevConfig = {
  mode: 'development',
  entry: ['webpack-hot-middleware/client', WEBPACK_SRC_CLIENT],
  output: {
    filename: 'client-[hash:4].js',
    publicPath: WEBPACK_ROOT,
  },
  devtool: '#source-map',
  stats: 'normal',
  module: {
    rules: [
      {
        test: /\.(less|css)$/,
        use: ['style-loader', 'css-loader', 'less-loader'],
        exclude: /node_modules/,
      },
    ],
  },

[…] etc.

我很好奇,欢迎任何帮助

【问题讨论】:

    标签: javascript typescript webpack


    【解决方案1】:

    未定义不可传播。那么如果?触发器然后结果是未定义的,并且您的代码实际上是...未定义的,这显然不起作用。

    使用 ??合并到一个空数组 ...(thing?. Prop ?? []),或者找到另一种处理 null/undefined 的方法(如 if 检查)

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 2017-10-07
      • 1970-01-01
      • 2020-03-02
      • 2020-03-24
      • 2020-11-13
      • 2020-05-15
      • 2017-12-19
      • 1970-01-01
      相关资源
      最近更新 更多