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

Passing an array of unknown shape

I have a simple function that I use to duplicate an array:

const data = (items) => {
  myData = items.slice()
}

Now items is an array of objects and these objects can be of any shape. How do I achieve this in TypeScript?

const data = (items: Array<any>) => {

This works but I am not sure if using any here is the best way.

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

>Solution :

You can achieve this by using generics, which will allow you to infer the input type

In the following example, I return the copy for demonstration purpose, so you can see what’s inferred for the output given T

// T extends unknown restricts[] the parameters to be of array type
const data = <T extends unknown[]>(items: T[]): T[] => {
  myData = items.slice()
  return myData;
}

// inferred as number[]
const outputA = data([1, 2, 3])

// inferred as string[]
cont outputB = data(['str1', 'str2'])

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