'how to cast json to typescript object
There initialized JSON data, I need to convert this as an type(mobx-state-tree) of object defined as belows,
const resultData = [
{
survey_id: 9,
title: 'Test Survey id9',
is_anonymous: false,
end_datetime: '2022-02-21T00:00:00+00:00',
category: {
full_url:
'https://s3.amazonaws.com/trivie-eventcategory-dev/W2V38X/f868184aece546c9_11.png',
is_archived: false,
label: 'Survey',
},
},
]
Models:
import { Instance, types } from 'mobx-state-tree'
export const SurveyAssignCategoryModel = types.model('SurveyAssignCategoryModel').props({
full_url: types.string,
is_archived: types.boolean,
label: types.string,
})
export const GetAssignedSurveysForUserResponseModel = types
.model('GetAssignedSurveysForUserResponseModel')
.props({
survey_id: types.number,
title: types.string,
is_anonymous: types.boolean,
end_datetime: types.maybeNull(types.string),
category: types.maybeNull(types.array(types.late(() => SurveyAssignCategoryModel))),
})
Here is the error message in IDE (it has category underlined in the object literal):
Type '{ full_url: string; is_archived: false; label: string; }' is not assignable to type 'IMSTArray<IModelType<{ full_url: ISimpleType; is_archived: ISimpleType; label: ISimpleType; }, {}, _NotCustomized, _NotCustomized>> & IStateTreeNode<...>'. Object literal may only specify known properties, and 'full_url' does not exist in type 'IMSTArray<IModelType<{ full_url: ISimpleType; is_archived: ISimpleType; label: ISimpleType; }, {}, _NotCustomized, _NotCustomized>> & IStateTreeNode<...>'
how to cast and use this object properly?
Solution 1:[1]
I don't work with mobx-state-tree, but I think it's error here:
...
category: types.maybeNull(types.array(types.late(...
category it's not array but I think map and here you don't need late.
try something this:
...
category: types.maybeNull(types.map(SurveyAssignCategoryModel))
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 | zbyso |

