I am striving to develop a function that can clone an array while maintaining the original data types. The current issue I am facing is that TypeScript is declaring the return type as any:
export function cloneArray(inputArray) {
return [...inputArray];
}
// result will have any[] as type
const result = cloneArray([1, 2, 3]);
Is there a way to instruct TypeScript to set the return type of cloneArray
to be the same as the input type, such as an array of numbers in this scenario?
Potential Solution
I am aware that I can achieve this using a type variable:
export function cloneArray<T>(inputArray): T[] {
return [...inputArray];
}
// result will have number[] as type (only because I specified T as number)
const result = cloneArray<number>([1, 2, 3]);
I am looking for a way to avoid the workaround mentioned above, as it requires me to define the type in advance.