【问题标题】:Using callback method type with rest parameters使用带有剩余参数的回调方法类型
【发布时间】:2021-10-02 19:12:15
【问题描述】:

家长:

const ParentComponent = () => {
  const childCompCallBack = (accountUrl: string, ...params: string[]) => {
    console.log(accountUrl);
    console.log(...params);
    ...
  };
 return (
  ChildComponent setAccounts={childCompCallBack}
 )
};

孩子:

export type queryParams = {
  setAccounts: (accountUrl: string, ...params: string[]) => void;
}

const ChildComponent = ({ setAccounts }: queryParams) => {
  setAccounts("https://xyz/", "drafts", "2")
};

我在尝试在childCompCallBack 参数中使用类型queryParams 时遇到问题。目前我的实现有效,但我想摆脱 childCompCallBack 中的隐式参数声明并使用子级导出的 queryParams 类型。 任何建议都会有所帮助。ty

【问题讨论】:

    标签: javascript reactjs typescript ecmascript-6 types


    【解决方案1】:

    如果您可以访问父文件中的queryParams,您可以简单地将您的变量设为子类型:

    const ParentComponent = () => {
      const childCompCallBack: queryParams['setAccounts'] = (accountUrl, ...params) => {
        console.log(accountUrl);
        console.log(...params);
        ...
      };
     return (
      ChildComponent setAccounts={childCompCallBack}
     )
    };
    

    【讨论】:

      【解决方案2】:

      你可以打破类型:

      export type setAccounts = (accountUrl: string, ...params: string[]) => void
      
      export type queryParams = {
        setAccounts : setAccounts
      }
      

      那么你就可以使用它了:

      const childCompCallBack : setAccounts = (accountUrl, ...params) => {
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-02
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        相关资源
        最近更新 更多