简体   繁体   English

如何为 map function 正确使用 TypeScript?

[英]How to use TypeScript correctly for map function?

I have this DB, and I'm trying correctly map the types when using Map function.我有这个数据库,并且在使用 Map function 时,我正在正确尝试 map 类型。 First time doing it so trying to learn but I'm stuck.第一次这样做,所以想学习,但我被卡住了。

Db D b

const db = {
  data: [
    {
      id: 1,
      contentType: ['video'],
      title: '1 to 1 Coaching: Sprinting Technique',
      author: {
        name: 'James',
        image: {
          alt: 'smiling.',
        },
      },
      image: {
        alt: 'Two footballers jostling for the ball with a coach watching in the background.',
      },
    },
  ],
}

For now I'm just using sample type of id and title but even here I'm stuck on how to correctly map it so TS does not complain:(现在我只是使用样本类型的idtitle但即使在这里我也坚持如何正确 map 它所以 TS 不会抱怨:(

App.tsx应用程序.tsx

type Data = {
  id: number
  title: string
}

interface Customer {
  id: number
  title: string
}

export default function Box(): JSX.Element {
  const [data, setData] = useState([db])
  return (
    <>
      {data.map(
        ({
          data: {
            id,
            contentType,
            title,
            author: {
              name,
              img: { src, alt },
            },
            image: { src, alt },
          },
        }): JSX.Element => {
          console.log(id)
          return <div css={mainBox}></div>
        },
      )}
    </>
  )
}

This issue has little to do with TS itself since the error is at object destructuring in parameters list of your map callback.这个问题与 TS 本身没什么关系,因为错误是在map回调的参数列表中的 object 解构。

When you apply object destructuring to the argument of the function, JS/TS assigns properties of the object to distinct variables with the same name (unless they are objects and they are destructured in a similar way).当您将 object 解构应用于 function 的参数时,JS/TS 将 object 的属性分配给具有相同名称的不同变量(除非它们是以类似的方式解构的对象)。

Let's have a look at author property destructuring:让我们看一下author属性解构:

...
            author: {
              name,
              img: { src, alt },
            },
...

This snippet will be treated as following:此代码段将被视为如下:

author.name property will be assigned to distinct name variable. author.name属性将分配给不同的name变量。 However,然而,

author.img won't be assigned to distinct img variable since it is an object and it is desctructured. author.img不会被分配给不同的img变量,因为它是一个 object 并且它是 desctructured。 It's properties would be assigned to distinct variables src and alt respectively.它的属性将分别分配给不同的变量srcalt

After that we have another property desturctured:之后,我们对另一个属性进行了分解:

    image: { src, alt },

Again, image won't be assigned to distinct variable since it's object being destructured.同样, image不会被分配给不同的变量,因为它是 object 正在被解构。 But it's properties should.但它的属性应该。

It's properties are src and alt .它的属性是srcalt And they should be set to variables with these names but we already have those names come from destructuring author.img .它们应该设置为具有这些名称的变量,但我们已经有这些名称来自解构author.img

So there is name collision in variables definition and that's why TS compiler raised an error.因此变量定义中存在名称冲突,这就是 TS 编译器引发错误的原因。

You may fix this by assigning properties to new variable names, for example, the following way:您可以通过将属性分配给新变量名称来解决此问题,例如,以下方式:

({
          data: {
            id,
            contentType,
            title,
            author: {
              name,
              img: { src: authorImgSrc, alt: authorImgAlt },
            },
            image: { src, alt },
          },
        }): JSX.Element => {
            // src refers to image.src, authorImgSrc refers to author.name.src
            // alt refers to image.alt, authorImgAlt refers to author.name.alt
        }

Here we explicitly assigned author.img properties to variables with different names so there is no name collision anymore.在这里,我们明确地将author.img属性分配给具有不同名称的变量,因此不再存在名称冲突。

The destructuring assignment technique might be really useful, there are more examples of it on MDN解构赋值技术可能真的很有用, MDN上有更多的例子

After that you might see that you might not even need map in the first place, because you used array destructuring here:之后,您可能会发现您甚至可能首先不需要map ,因为您在这里使用了数组解构:

const [data] = useState([db]);

And after that you may have access to it's internals directly:之后,您可以直接访问它的内部:

const {img} = data.data.author;

So you may want to either remove .map (and render db entry directly) or not use array destructuring in data variable initialization:因此,您可能希望删除.map (并直接呈现 db 条目)或不在data变量初始化中使用数组解构:

const data = useState([db]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM