Imagine you have a function that:
- receives an object with multiple properties and a property name;
- checks if the property holds an array;
- if it does, performs an action (such as printing the values it contains)
Here's an illustration:
function processIfPropertyIsArray(values, field) {
if (Array.isArray(values[field])) {
values[field].map(x => console.log(x));
}
return null;
}
The following types appear to be functioning correctly, with ArrayValues<T>
exclusively retrieving array-like types from T
's properties:
type StringKey<T> = keyof T
type ArrayValues<T> = T[
{
[K in keyof T]: T[K] extends any[] ? K : never
}[keyof T]
]
type X = {
foo: string,
bar: string[],
qux: number[],
}
// const arrayValues: string[] | number[] -> Success!
const arrayValues: ArrayValues<X> = ['a'];
However, when attempting to apply these types in the function above, Typescript throws an error:
function processIfPropertyIsArray<T>(values: T, field: keyof T) {
if (Array.isArray(values[field])) {
const arrayValue = values[field] as ArrayValues<T>;
arrayValue.map(x => console.log(x));
}
return null;
}
https://i.sstatic.net/CJQ6L.png
Property 'map' does not exist on type 'T[{ [K in keyof T]: T[K] extends any[] ? K : never; }[keyof T]]'
Why is this happening? What could be the issue/mistake here?