I am currently developing a function that is responsible for parsing a CSV file and returning an array of objects with specified types. Here is a snippet of the code:
type KeyToTransformerLookup<T> = {
[K in keyof T as T[K] extends string ? never : K]: (
stringValue: string
) => T[K];
};
export default function csvToArray<T>(
csv: string,
keys: Array<keyof T>,
keyToTransformerLookup: KeyToTransformerLookup<T>,
ignoreFirstLine = false
): T[] {
const rows = csv.split(/\n(?=.)/);
if (ignoreFirstLine) {
rows.shift();
}
return rows.map((row) => {
const values = row.split(/(?!\B"[^"]*),(?![^"]*"\B)/g);
const rowObject: Record<any, any> = {};
keys.forEach((key, index) => {
const stringValue = values[index];
if (key in keyToTransformerLookup) {
rowObject[key] = keyToTransformerLookup[key](stringValue);
return;
}
rowObject[key] = stringValue;
});
return rowObject as T;
});
}
Type 'keyof T' cannot be used to index type 'KeyToTransformerLookup<T>'.
The issue arises because after mapping K in keyof T
, the resulting type is no longer a subset of keyof T
. This can be frustrating as I am not modifying the keys themselves, but simply checking their existence in keyToTransformerLookup
. Therefore, I am looking for a way to properly index keyToTransformerLookup
in order to satisfy TypeScript.