skip to Main Content

I am getting this error Type MyInterface' is not assignable to type 'string'. I understand it, but can’t come up with a good solution. MyInterface only returns one item which is a string. Here is the code running.

export interface MyInterface {
  pulledCoolData: string;
}

const getData = async (passedData: string): Promise<MyInterface> => {
  const coolData = await getDataFromAPI(passedData);

  return coolData;
};


getData(data.myData).then(response => {
    window.location.href = response;//the error is on this line because reponse is type MyInterface and it is expecting a string to be passed
});

2

Answers


  1. I think you forgot to get pulledCoolData from MyInterface:

    getData(data.myData).then(response => {
        window.location.href = response.pulledCoolData;
    });
    

    I have no TypeScript experience, though, so this may be incorrect.

    Login or Signup to reply.
  2. The issue is there due to the type mismatch. The response you get back from the getData function is of the type MyInterface, which is an object, whereas window.location.href is expecting a plain string.

    To fix this you will want to reference the pulledCoolData property from the response object, since that is the actual string you want:

    Code Snippet:

    getData(data.myData).then(response => {
        window.location.href = response.pulledCoolData;
    });
    

    By updating it in this way, you’re passing the desired string value from within the MyInterface object to window.location.href.

    Update:
    It seems like there is a discrepancy between the data structure you anticipate and what the API is delivering.

    We need to break it down to isolate the issue.

    1. Check the RAW Data:
      Inspect what getDataFromAPI(passedData) returns. Try to console.log(coolData) before you return it in your getData function. This will let you see the structure of the returned data.

    The Script:

    const getData = async (passedData: string): Promise<MyInterface> => {
      const coolData = await getDataFromAPI(passedData);
      console.log('Returned data from API:', coolData);
      return coolData;
    };
    
    1. Adjust according to Data:
      If coolData doesn’t have the pulledCoolData property, you’ll need to adjust MyInterface or how you access the data.

    2. Handle Undefined Correctly:
      It is wise to manage potential undefined values effectively. Before utilizing response.pulledCoolData, ensure it’s present:

    The Script:

    getData(data.myData).then(response => {
        if (response && response.pulledCoolData) {
            window.location.href = response.pulledCoolData;
        } else {
            console.error('Unexpected response format:', response);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search