mardi 8 août 2017

Properly validate the JSON.parsed data in TypeScript

I'm creating a small module for the angular and I'm stuck with condition where I check my JSON.parsed data if they're correct.

read(): Position|null {
    try {
        ...
        let parsedData  = JSON.parse(data);
        if (parsedData && parsedData.x && parsedData.y)
            return new Position(parsedData.x, parsedData.y);
    } catch (e) {
        ...
    }
    return null;
}

It seems like not a great solution to me as if there's more properties in the object I previously stringified, then I'd need to check for each one of them. I'm also not sure about what happens when the parsed data are null. Is there any other solution for checking the strigified data? Thanks

Aucun commentaire:

Enregistrer un commentaire