Create an alias name for a property in Typescript

Viewed 521

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 Answers

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

Related