Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The property 'someProp' does not exist on value of type 'object' in Typescript

I have a JSON object returned to me from an $.ajax call. I get my object from my response like so:

var parsedJSON = $.parseJSON(jqXHR.responseText);

The object itself that gets passed from the server has a ResponseStatus property, and in that ResponseStatus property, there is an ErrorCode and Message. I thought I'd just be able to do this:

var r = parsedJSON.ResponseStatus;

But I get the error: The property 'ResponseStatus' does not exist on value of type 'object'

Because this is typescript, when I try to save the file and then have VS create my Javascript, it won't.

Am I missing something super obvious here? I can create an interface and cast the object to the interface like this:

var parsedJSON: IHttpResponseStatus = <IHttpResponseStatus> $.parseJSON(jqXHR.responseText);
var r = parsedJSON.ResponseStatus;

But this seems like overkill to get a property, and pretty wrong. Thanks in advance.

Edit: Oh nevermind, you can use array notation and TS doesn't care. Whoops!

like image 807
Crystal Avatar asked Nov 29 '25 15:11

Crystal


1 Answers

That's becuase jquery.d.ts defines parseJSON as:

parseJSON(json: string): Object;

It should be any. You can cast the result yourself to avoid creating an interface

var parsedJSON = <any> $.parseJSON(jqXHR.responseText);
var r = parsedJSON.ResponseStatus;

or:

var parsedJSON:any = $.parseJSON(jqXHR.responseText);
var r = parsedJSON.ResponseStatus;

I've sent a pull request as well : https://github.com/borisyankov/DefinitelyTyped/pull/554

like image 143
basarat Avatar answered Dec 02 '25 05:12

basarat