2

I have type like this:

export type Model = {
  Id: number,
  Name: string
}

and a JSON response like this: {"id": 0, "name": "User"}.

After Axios parsed that response (const response = await Axios.get<Model>(source)), I get next object:

Id: undefined Name: undefined id: 0 name: "User"

How correctly parse response to PascalCase model kind?


`

Tim Perry
  • 11,766
  • 1
  • 57
  • 85
  • Take a look at [this](https://stackoverflow.com/questions/12931828/convert-returned-json-object-properties-to-lower-first-camelcase). Is what are you looking for? – Carlo Corradini Jul 04 '20 at 17:04

1 Answers1

2

There are many ways to do this, but whatever happens, you need to change your types, as they're not correct at the moment, and you need to manually transform your result object.

The types currently say that Axios.get will return a model with Id and Name keys, which is definitely wrong (it will return a model with id and name keys). You can transform this result, but can't easily change the first return value there, so you need to correct that.

Once that's correct, you need to transform the JSON response to the model you want. One option is to use lodash, which makes this fairly easy.

A full example might look like this:

export type Model = {
  Id: number,
  Name: string
}

// Get the raw response, with the real type for that response
const response = await Axios.get<{ id: number, name: string }>(source);

// Transform it into a new object, with the type you want
const model: Model = _.mapKeys(response,
  (value, key) => _.upperFirst(key) // Turn camelCase keys into PascalCase
);

There are lots of other ways to do the last transformation step though, this is just one option. You might also want to think about validation first too, to check the response data is the shape you expect, if that's a risk in your case.

Tim Perry
  • 11,766
  • 1
  • 57
  • 85
  • Thank you! It seems, using PascalCase models in TS is a bad approach. – Влад Макух Jul 04 '20 at 17:22
  • 1
    It's not so much that it's bad with TypeScript, it's that your model doesn't match your API. TypeScript doesn't convert anything for you, so you have to match them, or do your own transforming. – Tim Perry Jul 04 '20 at 22:22