I am trying to return a typed object using the Axios API. I am using the generic type to declare that I am returning an instance of GetSliceResponse
but unfortunately Axios seems to still return an object of type any.
My code looks like this
export class GetSliceResponse
{
Success: boolean;
}
Axios.post<GetSliceResponse>("myurl/Get", request).then(o => {
var expectedResult = (new GetSliceResponse()) instanceof GetSliceResponse;
//expectedResult = true;
var unexpectedResult = o.data instanceof GetSliceResponse;
//unexpectedResult = false;
});
The Http response is exactly what you would expect:
{"Success":false}
As the above code illustrates I can correctly create an instance of my type using the new
syntax but the Axios data property appears unaffected by the type declaration.
I am trying to return a typed object using the Axios API. I am using the generic type to declare that I am returning an instance of GetSliceResponse
but unfortunately Axios seems to still return an object of type any.
My code looks like this
export class GetSliceResponse
{
Success: boolean;
}
Axios.post<GetSliceResponse>("myurl/Get", request).then(o => {
var expectedResult = (new GetSliceResponse()) instanceof GetSliceResponse;
//expectedResult = true;
var unexpectedResult = o.data instanceof GetSliceResponse;
//unexpectedResult = false;
});
The Http response is exactly what you would expect:
{"Success":false}
As the above code illustrates I can correctly create an instance of my type using the new
syntax but the Axios data property appears unaffected by the type declaration.
1 Answer
Reset to default 4Just because something has the same properties as the class does not mean it is an instance of the class. In your case the response from the server is probably parsed using JSON.parse
which will create simple objects. Only objects created using new GetSliceResponse
will actually be instances of the class.
The type parameter to the post method is meant to help describe the shape of the response but will not actually change the runtime behavior (nor could it, genetics are erased during pilation).
This being said, you can still access the properties of the object as if the object was an instance of the class, the only thing that will not work is instanceof
and don't expect any method to be present.
If you want to make sure nobody uses instanceof
by mistake you can make the type am interface instead.
If you really need the class you can create an instance using new
and use Object.assign
to assign all fields
export class GetSliceResponse
{
Success: boolean;
}
Axios.post<GetSliceResponse>("myurl/Get", request).then(o => {
o = Object.assign(new GetSliceResponse(), o);
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745190321a4615833.html
评论列表(0条)