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