简体   繁体   English

使用 TypeScript 和 Webpack 的可选链接失败的传播

[英]Spread with optional chaining failing with TypeScript and Webpack

I have an application with TypeScript bundled with webpack.我有一个 TypeScript 与 webpack 捆绑在一起的应用程序。

I am using spread operators:我正在使用传播运算符:

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

When members is undefined, I get an error:members未定义时,我收到一个错误:

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

But this only happens on Firefox;但这仅发生在 Firefox 上; on Chrome, for example, it pass.例如,在 Chrome 上,它通过了。 May it be related to my webpack build or the tsconfig?可能与我的 webpack 构建或 tsconfig 有关吗?

This is the 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/**/*", "./*"]
}

This is my webpack这是我的 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.

I'm really curious, any help will be welcome我真的很好奇,欢迎任何帮助

Undefined isn't spreadable.未定义是不可传播的。 So if the?那么如果? triggers then the result is undefined, and your code is effectively...undefined which obviously doesn't work.触发器然后结果是未定义的,并且您的代码实际上是......未定义的,这显然不起作用。

Use??利用?? To coelesce to an empty array...(thing?. Prop?? []), Or find another way to handle null/undefined (like an if check)合并到一个空数组...(东西?。道具??[]),或者找到另一种处理空/未定义的方法(如 if 检查)

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

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