Home > OS >  Passing an array of unknown shape
Passing an array of unknown shape

Time:08-20

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.

CodePudding user response:

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'])

CodePudding user response:

You didn't specify what myData is and how you want to use it. I guess you want that function to return the copied array? In that case you can add a generic to data so the type of the returned array gets inferred from what you pass as a parameter.

const data = <T,>(items: T[]): T[] => {
    return items.slice()
}

const newArray = data([3,4,5])
// const newArray: number[]

playground link

CodePudding user response:

The other answers are really good, but I don't like them for more complex objects since I don't think they do a deep copy, but this does it :

const a = (items: any[]): any[] => {
    const copyArray: any[] = []
    items.forEach((i) => copyArray.push({...i}));
    return copyArray;
}

or

const a = (items: any[]): any[] => {
    const copyArray: any[] = []
    items.forEach((i) => copyArray.push(Object.assign({}, i)));
    return copyArray;
}

Unfortunately for list strings it's not the best since it will split them into arrays.

playground

  • Related