hegel
hegel copied to clipboard
How to write a clone function?
I would like to scope this only to arrays for now. How do I write a clone function that clones tuples and arrays while preserving types?
I get an array type back with this:
function clone<T>(arr:T): T {
return [].concat(arr)
}
let cloned = clone([1,2,3])
this works
function clone<T>(arr: Array<T>): Array<T> {
return Array.from(arr)
}
let cloned = clone([1, 2, 3])
but i don't think you can copy tuples for now
also concat on empty array should work i guess
But the problem exists in the type inference algorithm. Will try to fix it.
Interestingly, this simply crashes:
function clone<T>(arr: Array<T>): Array<T> {
const array: Array<T> = Array.from(arr);
return array;
}
Fixed. And will be available in the next release. Thank you for the issue :3
// Could not deduce type "(ArrayLike<T> | Iterable<T>) => Array<T>" arising from the arguments unknown,(ArrayLike<T> | Iterable<T>) => Array<T>.
// Please, provide type parameters for the call or provide default type value for parameters
// of "<T>(T, T) => T" function.
// WAT??
const clone01 = arr => Array.from(arr)
// (ArrayLike<T> | Iterable<T>) => Array<T>
// this is same but works
function clone01_1(arr) {
return Array.from(arr)
}
// <T>(T) => $Immutable<Array<T | unknown>>
// this one looks wrong
const clone02 = arr => [].concat(arr)