2

context: I have to do a post request to a server with a body of interface with properties title_string,created_at,etc

interface IPostBody{
      titleString:string;
      createdAt:string;
      ....
    }

I need to use this interface here

const requestBody:IPostBody={
  title_string:'hehe';
  created_at:'my home';
}

as you can see, the names don't match up so it will raise type missing errors.

is there a way I could solve this without changing the camelCase names in the interface definition

  • 1
    It sounds like you're looking for [this](https://tsplay.dev/wX2LQm) where you transform the type `IPostBody` to a version with snake_case keys, as in `const requestBody: CamelKeysToSnake = ...` . Is that right? (If so, then this question is probably a [duplicate](https://stackoverflow.com/questions/64932525/is-it-possible-to-use-mapped-types-in-typescript-to-change-a-types-key-names). Let me know.) – jcalz Dec 06 '21 at 01:05
  • @jcalz yea i guess its a duplicate , thanks – GeorgeMenezes Dec 06 '21 at 10:37

1 Answers1

2

You could define a transformer function that will change the keys to camel casing:

function transformBody(body: any) : IPostBody {
 return {
   titleString: body.title_string,
   createdAt: body.created_at
   // and so on...
 }
}

Or create a function that automatically convert all keys to camcel case. See Convert returned JSON Object Properties to (lower first) camelCase

Antoine Gagnon
  • 874
  • 7
  • 13