首页 > 解决方案 > What is the correct way to use object destructing in this situation?

问题描述

I recently added ESLint to a project to improve the project and my skills.

const server = app.listen(config.port, () => {
    const host = server.address().address;
    const port = server.address().port;
    log.info(`API server listening on host ${host}, port ${port}`);
});

ESLint says to use destructuring for line 2 and 3.

The 'quick fix' that VSCode gives me is

const server = app.listen(config.port, () => {
    const { host } = server.address();
    const { port } = server.address();
    log.info(`API server listening on host ${host}, port ${port}`);
});

This feels... wrong somehow.
If the quick fix isn't actually the correct fix, can someone educate on the proper way to use destructuring here.
If this is indeed the correct fix, can someone explain reasons this is better than it was before.

I don't want to blindly follow ESLint but I'm not about to ignore the advice of a tool like ESLint either. Like I said, I want to learn.

标签: javascripteslint

解决方案


您可以在将字段映射到不同名称的同时破坏该值。

const mockServer = {
  address() {
    return {
      address: 'foo',
      port: 3000,
    };
  },
};

const { address: host, port } = mockServer.address();

console.log(host, port);


推荐阅读