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

后端 未结 2 1634
甜味超标
甜味超标 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:22

    What you are seeing is not a type annotation, but a property in an object pattern. Let's simplify your example to help see what is going on.

    Here's a function that is easy to understand:

    f = (h) => [h.x, h.y]
    

    The function f takes in an object h and returns an array with h.x and h.y. Now in modern JavaScript one does not have to pass in an object and break it all apart in the function body. Instead, we make the parameter section of the function be a pattern so that we don't need to bother with that h variable at all. So we could rewrite it like this (in a way that parallels your example):

    f = ({x: xValue, y: yValue}) => [xValue, yValue]
    

    So, exactly like before, you can pass to f any object that has x and y properties and it will return an array of the values at those properties.

    Here it is in action:

    > f = (h) => [h.x, h.y]
    [Function: f]
    > f({x:1, y:2, z:3})
    [ 1, 2 ]
    > f = ({x: xValue, y: yValue}) => [xValue, yValue]
    [Function: f]
    > f({x:1, y:2, z:3})
    [ 1, 2 ]
    

    As an aside, normally one would skip the xValue and yValue part and have:

    f = ({x: x, y: y}) => [x, y]
    

    which due to shorthand property notation is just:

    f = ({x, y}) => [x, y]
    

    but as @BhojendraRauniyar writes in another answer, there are capitalization conventions in the framework this code is being used with.

提交回复
热议问题