'Typescript does not recognize the correct generic type with index access [duplicate]
I am trying to process nested arrays of two different objects with the same type.
The type ArrayProperties returns the correct type definition.
type ArrayProperties<T> = {
[P in keyof T as T[P] extends Array<any> ? P : never]: T[P];
}
I do not understand why Typescript won't recognize the correct types in the function body of concatArrays.
function concatArrays<Type extends object, Prop extends keyof ArrayProperties<Type>>
(arr1: Type, arr2: Type, prop: Prop) {
const a = arr1[prop];
const b = arr2[prop];
// Why are a and b of type any and not of type Array?
return a.concat(b); // `Property 'concat' does not exist on type 'Type[Prop]'.`
}
Example:
const arr1 = {
bla: 'str',
foo: [1, 2]
};
const arr2 = {
bla: 'ing',
foo: [3, 4]
};
const result = concatArrays(arr1, arr2, 'foo');
// result type should be number[]
const typeError = concatArrays(arr1, arr2, 'bla'); // type error => correct
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
