【问题标题】:Destructure using rest parameters使用剩余参数进行解构
【发布时间】:2021-10-11 17:58:33
【问题描述】:

我正在尝试根据传递给钩子的其余参数来解构 React 上下文。

假设我正在传递一个枚举数组,并且只想返回传递给钩子的那些。

这是我的接口上下文类型

enum ConfigItem {
  SomeItem = 'SomeItem',
  AnotherItem = 'AnotherItem',
}

type Config = Record<ConfigItem, boolean>;

type ConfigState = {
  config: Config;
}

还有钩子本身

const useConfig = (...configArgs: ConfigItem) => {
  const configContext = useContext(ConfigContext);
  
  const { config } = configContext;
  const { ...configArgs } = config;  // Duplicate identifier 'configArgs'.

  return configArgs;
}

我想这样使用它

const config = useConfig(ConfigItem.SomeItem, ConfigItem.AnotherItem);

这将返回一个具有相关属性的对象。我可能想传递一个参数,但可能有很多。

上述 const 将返回 this(真/假是上下文中的任何内容,但不在问题范围内)

{
  SomeItem: true/false,
  AnotherItem: true/false,
}

但如果我只通过其中一个,我希望看到一个属性。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    就其性质而言,其余参数是数组,因此您需要一个数组类型:

    const useConfig = (...configArgs: ConfigItem[]) => {
    //                                          ^^−−−−−−−−−−−−−−−−−−−−−−−−−
    // ...
    

    如果你只传递一个参数,数组将只有一个元素,但它仍然是一个数组。


    在你说过的评论中:

    我的问题是如何只返回提供的 args 属性,但感谢您的更正。

    如果您的意思是在创建要返回的对象时遇到问题,您可以通过以下几种方式来实现;我可能倾向于Object.fromEntries(如果针对的是 ES2019 之前的环境,则需要 polyfill):

    const useConfig = (...configArgs: ConfigItem[]) => {
        const configContext = useContext(ConfigContext);
        
        const { config } = configContext;
        return Object.fromEntries(
            configArgs.map(itemKey => [itemKey, config[itemKey]])
        ) as Record<ConfigItem, boolean>;
    };
    

    你可能需要一个类型保护来避免

    【讨论】:

    • 我的问题是如何只返回提供的 args 属性,但感谢您的更正。
    • @LazioTibijczyk - 啊,我以为您在参数类型方面遇到了问题。我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2017-05-28
    • 2020-06-09
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多