【问题标题】:What is wrong with typescript deconstructing operator in this snippet?此代码段中的打字稿解构运算符有什么问题?
【发布时间】:2020-09-22 00:53:08
【问题描述】:

我的 IDE 在这个 typescript (tsx) sn-p 中显示 2 个错误:

// @ next line: TS2300: Duplicate identifier 'boolean'.
const SlidesControl = ({ previous: boolean, next: boolean }) => {

  return (
    // @ next line: TS2304: Cannot find names 'previous' and 'next'.
    <nav>TODO {previous} {next}</nav>
  )
}

为什么?

【问题讨论】:

    标签: typescript ecmascript-6 react-tsx


    【解决方案1】:

    const SlidesControl = ({ previous: boolean, next: boolean }) - 重命名参数(JS 特性,ES6),在你的情况下是 2 个名为 boolean 的参数

    你需要类型描述(TS特性):

    const SlidesControl = ({ previous, next }: { previous: boolean, next: boolean }) => {
        return (
            <nav>TODO {previous} {next}</nav>
        );
    };
    

    另一种方式:

    type ISlidesControlProps = { previous: boolean; next: boolean };
    
    const SlidesControl = ({ previous, next }: ISlidesControlProps) => {
        return (
            <nav>
                TODO {previous} {next}
            </nav>
        );
    };
    

    React 中更受欢迎的方式:

    type ISlidesControlProps = { previous: boolean; next: boolean };
    
    const SlidesControl: React.FC<ISlidesControlProps> = ({ previous, next }) => {
        return (
            <nav>
                TODO {previous} {next}
            </nav>
        );
    };
    

    【讨论】:

    • 谢谢。难道没有比重写每个参数来指定类型更简洁的语法吗?
    • @dragonmnl 不,另一种方法是在组件外部创建类型:type ISlidesControlProps = { previous: boolean; next: boolean }; 并使用:const SlidesControl = ({ previous, next }: ISlidesControlProps) =&gt;
    • React 最佳实践:const SlidesControl: React.FC&lt;ISlidesControlProps&gt; = ({ previous, next })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2021-02-15
    • 2018-05-06
    • 2011-03-08
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多