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

2
  • 1
    It sounds like you're looking for this where you transform the type IPostBody to a version with snake_case keys, as in const requestBody: CamelKeysToSnake<IPostBody> = ... . Is that right? (If so, then this question is probably a duplicate. Let me know.) Commented Dec 6, 2021 at 1:05
  • @jcalz yea i guess its a duplicate , thanks Commented Dec 6, 2021 at 10:37

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.