If you simply want to bypass the ts-ignore here are a few things you can do
- use a function that bypasses type checking
for (let columnInfo of (dbResult.rowDescription || {columns:[]}).columns) {
Object.assign(obj, {[columnInfo.name] : dbResult.rows[i][columnInfo.index - 1]});
}
- cast as keyof T
for (let columnInfo of (dbResult.rowDescription || {columns:[]}).columns) {
obj[columnInfo.name as keyof T] = dbResult.rows[i][columnInfo.index - 1];
}
- since you casted the array as
Array<T>
, you don't need to cast obj as T
const obj: any = {};
for (let columnInfo of (dbResult.rowDescription || {columns:[]}).columns) {
obj[columnInfo.name] = dbResult.rows[i][columnInfo.index - 1];
}
objArr[i] = obj;
To explain what is happening...
Current there are no restrictions on T, saying <T>
T can be a string
, number
, object
, Symbol
.. etc..
you can add restrictions on T
by using extend
ie.
<T extends object>
would ensure that T would descend from type object
.
Note: this would not fix your issue. extends
is not the same as equals
.
ie.. In your original function doing
type T = Record<string, any>
const obj = {} as T;
would solve your issues aswell. However doing
const mapDbResultToModelArray = <T extends Record<string, any>>(dbResult: QueryArrayResult<Array<string>>): Array<T> => {
const objArr: Array<T> = [];
for (let i = 0; i < (dbResult.rowCount || 0); i++) {
const obj = {} as T;
would not. You would still have an indexing error.. That is because in the former exampe T
really is Record<string, any>
but in the ladder example T
only inherits from Record<string, any>
but could still be of a more specific type ie. T = Record<'key1', 'key2', any>
this is why casting obj[columnInfo.name as keyof T]
will always work because if the keys are string
then keyof T
will be string
but if the keys are 'key1' | 'key2'
then keyof T
will be key1' | 'key2
So even if you typed it out better you could still have issues but hope you would understand them better.
When I got started with TS things like this did seem very annoying, but over time usually investigating issues like this helps you understand the code more deeply. ie. even though since you wrote the code and you know what is happening, this will likely be correct at run time, but ts will highlight what could possibly go wrong if minor mistakes are made.
So do not be discouraged from asking to get a deeper understanding.