Currently, I am working on parsing a CSV file and my goal is to convert the rows into objects. The function that I have written for this purpose appears like the following:
function dataToObjects<T extends SomeBasicObjectType>(data: string[][]): T[] {
const [rawHeaders, ...rows] = data
const headers = rawHeaders as Array<keyof T>
const dataAsObjects = rows.map((row) => {
const dataObject = Partial<T> = {}
row.forEach((dataPoint, idx) => {
// TypeScript allows this line without any issues
const header = headers[idx] as keyof T
if (!header) {
// throw some error
}
// However, the type error occurs here: Type 'string' is not assignable to type 'T[keyof T]'
dataObject[header] = dataPoint
})
return dataObject
})
return dataAsObjects
}
I have tried to simplify the example code as much as possible (and noted the error point in comments) so please excuse any imperfections. This sample reflects my attempts to tackle the problem by making various type casts.
You can test out this code (exactly as it is) on the TypeScript Playground to observe the error.