【问题标题】:Destructed object declaration in TypeScriptTypeScript 中的破坏对象声明
【发布时间】:2023-01-26 18:15:58
【问题描述】:

我可以像这样声明被破坏的函数参数:

const List = ({ items, css }: { items: string[], css: string[] }) => {
    
}

但我不喜欢我有冗余代码。有没有办法声明它

const List = ({ items of string[], css of string[] }) => {
    
}

正如我在 React 中通常需要的那样,我想我不能在没有“对象包装器”的情况下传递参数。有没有人有解决方案,尤其是在 React 组件中传递参数?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    不幸的是不可能。关于这个问题,有一个长期运行的 GitHub 线程 here,不幸的是,还没有任何具体计划引入任何新语法来帮助解决这个问题。

    【讨论】:

      【解决方案2】:

      如果你打算使用 TypeScript,你只需要习惯它比 JavaScript 更冗长的事实。

      如果您只是想将“类型语法复杂性”从组件实现中移开,那么您可以使用 type alias,如下所示:

      TS Playground

      type ListProps = {
        items: string[];
        css: string[];
      };
      
      const List = ({ items, css }: ListProps) => {
        // Component implementation
      };
      
      

      【讨论】:

        猜你喜欢
        • 2017-12-14
        • 2019-12-02
        • 2021-09-19
        • 1970-01-01
        • 1970-01-01
        • 2010-12-25
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        相关资源
        最近更新 更多