These types of conversions are common for handling API data coming in
Here's how I handle these type of conversions:
types/GithubRepo.ts
export interface GithubRepo {
id: number;
name: string;
description: string;
stars: number;
}
export const convertIntoGithubRepo = (githubRepoFragment: any): GithubRepo => ({
id: githubRepoFragment.id,
name: githubRepoFragment.name,
description: githubRepoFragment.description || '',
stars: githubRepoFragment.stargazers_count,
});
Usage
import { convertIntoGithubRepo } from 'types/GithubRepo';
const githubRepo = convertIntoGithubRepo(someGithubRepoFragment);
For this example, I am defining a type, then defining methods to copy an object of type any over to a type of GithubRepo
During this conversion, we can see that I'm checking for a descriptions existence on the any object, and adding a blank if one is falsy
yin your above code