'Error: The type cast expression is expected to be wrapped with parenthesis when using get function

im new to javascript and im trying to make a get request to a youtube API. I have preconfigured a few things related to the request before making it using axios. However, i think my question is more related to the use of the get function.

My predefined configuration for the request is stored under the 'youtube' object. Here is the code uesd to create it

import axios from 'axios';


const KEY = 'AIzaSyDVd1jDhcZdtJb--1_ncBqpL0Gxgfs9ys8';

export default axios.create({

    baseURL: 'https://www.googleapis.com/youtube/v3',
    params: {
        part: 'snippet',
        maxResults: 5,
        key: KEY

    }
});

My question is related to when i use the get function using these settings.

The code below gave me the following error: "Parsing error: The type cast expression is expected to be wrapped with parenthesis"

onTermSubmit = (term) => {

        youtube.get('/search', 
            params: {
                q:term
            }
        );
    };

But when i add parenthesis around params it works fine:

onTermSubmit = (term) => {

        youtube.get('/search', {
            params: {
                q:term
            }
        });
    };

Can someone explain why including the parenthesis solves this error, as well as what the error actually means in the first place?



Solution 1:[1]

Without the curly braces (they aren't parentheses), your code would be invalid JavaScript because you have a property initializer (params: {q:term}) outside an object literal, where the parser is expecting an argument for get. I'm guessing from the error message you're using TypeScript, which is trying to interpret the part after params: as a type expression.

Adding the {} fixes it because you need to wrap that property initializer in an object literal, so you're passing an object as the second argument to get.

Solution 2:[2]

Becase you not include the {} in this.setState methods:

  1. you correct this.setState({posts: response.data})

Solution 3:[3]

Initially I was using this:

this.setState( state: {query: query});

But when I got the error, after adding parentheses like below I have added. It works for me.

this.setState( {state: {query: query}});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder
Solution 2 Khadim H.
Solution 3 Suraj Rao