Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object type doesn't inherit all native obj methods

I create a type for a custom object shape like this:

type A = {
  readonly prop1: string;
  readonly prop2: string;
}

Then in a method I’m using it like so:

const getStuff = (obj: A) =>
   obj.reduce((acc, curr) => {
     ...
   })
}

It’s complaining that property 'reduce' does not exist on type A. I assumed A as an object type would inherit all the native methods of a JS object, but I guess not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can a I tell it to do that?

>Solution :

Because native javascript object doesn’t have a reduce method. Try obj.toString() or obj.hasOwnProperty(). Maybe you wanted to Array.reduce? If so, do it like this:

type A<T>  =  {
    readonly prop1: string;
    readonly prop2: string;
} & Array<T>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading