#Newbie using transformer functions from one interface to another

10 messages · Page 1 of 1 (latest)

vocal arch
#

I'm a bit new to using Typescript.

I am trying to implement a basic transformer function that is used when data is fetched from an api, then converted / transformed for the front end use.

interface ApiResponse<T> {
  data: T | null;
  error: string | null;
  pending: boolean;
}

interface UserDTO {
  ID: string;
  FirstName: string;
  LastName: string;
}

interface User {
  id: string;
  fullName: string;
}

function transformUser(user: UserDTO): User {...} 
function fetchUser(id: string): UserDto {...}
function handleResponse(request: Promise<T>): Promise<ApiResponse<T>> {...}
async function getUser(id: string): ApiResponse<User> {
  const result = await handleResponse(fetchUser);
  if (result.error) return result;
  result.data = transformUser(result.data);
  return result;
}

The issue i am having is that at result.data = transformUser(result.data), Type ApiResonse<UserDTO> is not assignable to type ApiResponse<User> and I am not sure how to deal with it. Chat GPT isn't helping either. It tries to return result as unknown as ApiResponse<User> but this doesn't remove the error.

winter fox
#

wouldn't you just return transformUser(result.data) there

vocal arch
winter fox
#

only 1 of data or error will be present, right?

#

if pending is false..?

#

you might want to use a union for that instead of the interface

#

anyways, ts has a static type system, so it's not going to change types from a mutation. result is ApiResponse<UserDTO>, and you can't change that by mutating result, that's not allowed
the general solution is to just make a new object with the right type, with spread syntax
so like, const transformedResult = { ...result, data: transformUser(result.data) }

vocal arch
#

Thank you! I think i've got it now! 😄

#

Not sure how to mark post as resolved.

winter fox
#

!resolved