Reshape JSON response using Type Assertions

202 Views Asked by At

I have an API I'm working with that returns keys in the wrong format. I'm curious if it's possible to fix these through type assertions or what the best approach may be for my problem (easiest to understand).

Let's take this body as an example:

{
  "home_address": "123 Street, Town, State U.S. ZIP",
  "phone_number": "555-555-5555"
}

What is the standard approach for reshaping the content? If I try to assert its type as-is, I get errors (obviously).

interface User {
  homeAddress: string;
  phoneNumber: string;
}

<User>{
  "home_address": "123 Street, Town, State U.S. ZIP",
  "phone_number": "555-555-5555"
}

Do I need to accept it as any, reshape it, then assert type? Or is there a more ergonomic way to do this in one fell swoop?

1

There are 1 best solutions below

0
Roberto Zvjerković On
interface User {
    homeAddress: string;
    phoneNumber: string;
}

interface UserResponse {
    home_address: string;
    phone_number: string;
}

const userResponse: UserResponse = {
    home_address: 'A',
    phone_number: 'B'
}

function rename(userResponse: UserResponse): User {
    return {
        homeAddress: userResponse.home_address,
        phoneNumber: userResponse.phone_number
    }
}