How is this type annotation working in React code without TypeScript?

后端 未结 2 1640
甜味超标
甜味超标 2020-11-30 16:18

I was looking at this code example on the ReactRouter page, and this piece is interesting:

const PrivateRoute = ({ com         


        
2条回答
  •  没有蜡笔的小新
    2020-11-30 16:36

    It's not a type annotation. It's a ES6 feature called destructuring rest parameters:

    First consider this example: (destructuring assignment)

    const test = myObject.prop
    // prop can be assigned in a variable
    const { prop } = myObject
    // but we want prop as a test variable
    // and can be written as
    const { prop: test } = myObject
    // which is similar to first line
    console.log(test)
    

    This is how we can pass in the parameters:

    ({ component, ...rest })
    
    // We're giving component name as Component
    
    ({ component: Component, ...rest })
    

    So, that you can use as you know lowercase component is invalid in react.


    Furthermore, I would suggest you to deep dive into the following blogs:

    Hackernoon: Understanding the destructuring assignment

    JavaScript Info: Destructuring assignment

    Codeburst: Destructuring assignment the complete guide

    Dev.to: Destructuring assignment - array

    Dev.to: Destructuring assignment - object

提交回复
热议问题