0

Typescript is giving me a compilation error with the following code:

console.log('YHISTORY:login: data = '+data);
let theData = JSON.parse(data);
console.log('YHISTORY:login: theData = '+JSON.stringify(theData));

It complains when compiling the second line as follows:

Error TS2345: Argument of type '{}' is not assignable to parameter of type 'string'

When I run this code the first line generates this console output:

YHISTORY:login: data = {"key":"4ba9f2eec3a59e76799a728f0dcda831b7f1fb66"}

The third line does not produce any console output. The following error is generated:

EXCEPTION: Error: Uncaught (in promise): TypeError: this is null

1 Answer 1

1

The error is not about assignment, it's about calling JSON.parse() function. Error looks like your data variable is already an object, when string is expected as function argument.

You can reproduce this error with this example:

var data = {};
JSON.parse(data);
Sign up to request clarification or add additional context in comments.

3 Comments

The typeof data is string.
Then there is not enough information for suggestion. In theory Error TS2345 can be incorrect while using incorrect .d.ts typescript definitions. It can be declared as object, but javascript still returns string. What about exception it looks like not aligned to this lines of code. I can suggest some scoping problems somewhere inside Promise handling, as an example using function(){} notation without binding this.
The problem tuned out to be using .then(function(data) { rather than .then((data:any)=>{ in the promise handler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.