代码之家  ›  专栏  ›  技术社区  ›  code4cash

声明了“string”,但从未读取其值

  •  0
  • code4cash  · 技术社区  · 2 年前

    正在尝试学习一些Typescript,但在早期遇到了错误。虽然我在学习教程,但还是遇到了不少错误。我已经注释掉了我收到的错误。如果有人能解释为什么会发生这种情况,以及如何修复它们,那将是非常棒的。

    import React from "react";
    
    interface IProps {
        name: string;
        age: number;
        title: string;
    }
    
    let Customer: React.FC<IProps> = ({
        name: string,
        //'string' is declared but its value is never read.
        age: number,
        title: string,
        //'string' is declared but its value is never read.
    }) => {
        return (
            <React.Fragment>
                <h2>Customer Component</h2>
                <ul className="list-group">
                    <li className="list-group-item">Name: {name}</li>
                    {/* //This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.ts(2746) */}
                    {/* 'name' is deprecated.ts(6385) */}
                    {/* lib.dom.d.ts(17329, 5): The declaration was marked as deprecated here. */}
                    <li className="list-group-item">Age: {age}</li>
                    {/* Cannot find name 'age'. */}
                    <li className="list-group-item">Title: {title}</li>
                    {/* Cannot find name 'title'. */}
                </ul>
            </React.Fragment>
        );
    };
    
    export default Customer;
    
    1 回复  |  直到 2 年前
        1
  •  3
  •   mc-user    2 年前
    let Customer: React.FC<IProps> = ({
        name: string,
        //'string' is declared but its value is never read.
        age: number,
        title: string,
        //'string' is declared but its value is never read.
    }) => {
    

    IProps 是使用特定类型定义所有属性的界面。右边你用它作为变量。你正在破坏对象,所以只需定义如下名称 {name, age, title} .

    如果您使用 name: string 在右侧,您重命名了 name string . 现场 名称 是从库中获取的,这就是为什么会出现错误。在第二行,没有 age 变量,将其重命名为 number .

    这是更新的代码。

    import React from "react";
    
    interface IProps {
      name: string;
      age: number;
      title: string;
    }
    
    let Customer: React.FC<IProps> = ({
      name,
      age,
      title,
    }) => {
      return (
        <React.Fragment>
          <h2>Customer Component</h2>
          <ul className="list-group">
            <li className="list-group-item">Name: {name}</li>
            <li className="list-group-item">Age: {age}</li>
            <li className="list-group-item">Title: {title}</li>
          </ul>
        </React.Fragment>
      );
    };
    
    export default Customer;
    
    

    你可以阅读 Object Destructuring assignment renaming the destructured fields