1

I am trying to clone an untyped object. I want to cast it while cloning. Here is a very simple code:

const typedOject: type123 = {...untypedObject} as type123;
typeObject.a = 1;

export interface type123 {
   a: number;
   b: number;
}

But the compiler complains: Property 'a' does not exist on type 'any[]'

So, why the new object is of type any?

Thanks

4
  • For tasks like this, I typically write a converter function that takes an any object and checks its attributes + builds up the return type Commented Oct 21, 2020 at 20:02
  • Also, I'm not seeing where there's a y in your above code Commented Oct 21, 2020 at 20:02
  • Copied from the development code. Fixed the typo. Commented Oct 21, 2020 at 20:03
  • I see. I've added an answer, please let me know if you have any other questions Commented Oct 21, 2020 at 20:14

1 Answer 1

1

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

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.