getLength
function appears to be functional
Upon inspection, these two functions seem quite similar (The second one may be more versatile as it can handle objects with properties other than just arrays):
During runtime, both functions essentially translate to the same javascript code.
function getLength<T>(
// v is an array of some type T
// This could be the type 'any',
// so I know nothing about what's inside
v: T[]
): number {
return v.length;
}
function getLength2<T extends any[]>(
// v is an array, I know nothing
// about what's inside
v: T
): number {
return v.length;
}
flattenArray
... well, it's not working as expected
If I apply the same logic here, I begin encountering type errors.
function flattenArray<T>(
a:T[][]
) : T[] {
return a.reduce((prev:T[], curr:T[]) => [...prev,...curr], [] as T[]);
}
function flattenArray<T extends any[]>(
a:T[]
) : T {
return a.reduce((prev:T, curr:T) => [...prev,...curr], [] as T);
}
Errors:
Type 'T[number][]' is not assignable to type 'T'
Conversion of type 'never[]' to type 'T' may be a mistake
From my perspective, I can cast the flattened array result to the desired type and bypass the type system by creating an empty array.
function flattenArray<T extends any[]>(
a:T[]
) : T {
return a.reduce((prev:T, curr:T) => [...prev,...curr] as T, [] as unknown as T);
}
This raises concerns for me. I believe there may be aspects of the type system that I am not fully grasping. When I specify T extends any[]
, I intend for T to possess at least all the properties of an Array. It could have more, but not less. Therefore, I should be able to treat T as an Array.
Any insights on this matter would be greatly appreciated!