Search code examples
javascriptreactjstypescriptcreate-react-app

Unexpected token when typing a function with destructuring assignment parameters in Create-React-App


I'm currently trying to define the type for a function whose parameters implement the destructuring assgnment syntax, for example

type somefunc = ({name} : {name: string}) => boolean;

It is giving me the following compile time error:

./src/App.tsx SyntaxError: /apps/src/App.tsx: Unexpected token, expected ")" (9:24)

It highlights the error on the : between {name} and {name: string}. However, I understand that this is the intended way to type destructure assignment parameters for a function.

My node version is node v10.13.0 while my react-scripts version is react-scripts v2.1.1, which should be sufficiently up-to-date.

How could I make the compiler understand this syntax?


Solution

  • If you want to type the parameter in the declaration of the function type, you should write it like:

    type somefunc = (param : {name: string}) => boolean;
    

    It says, the function (=>) returns a boolean and takes one parameter of type object {...} with an attribute name of type string.

    And then you can use destructuring in the definition of the function:

    const myfn: somefunc = ({name}) =>  {
        console.log('Name: ', name);
        return true;
    }
    
    myfn({name: 'John'});