I'm new to TypeScript, and trying to slowly migrate an existing JS (react) project to TypeScript.
I have a function executing a query:
/**
* Run a Query against the currently connected database
* @param {String} sql Query to run
* @param {Object[]} Array of objects to be used in the prepared statement
* @returns {Promise<Object[]>} Promise resolving after query is done. Returns an array of arrays with the result.
*/
const query = (sql, params) => {
//Database stuff
}
And I'm calling this in numerous locations:
const result = await query('SELECT count(*) as cnt from Table id=?',[2]')
return result[0].cnt
The last line gives an error, because the field 'cnt' is unknown. How to best solve this? The return type is always Object[], but the content ob the object depends on the query.
Any suggestions how to best move this code to TS?
CodePudding user response:
You should probably be telling you "Database stuff" what kind of return type it can expect:
const query = function <T>(sql:string, params:object):Array<T> {
//Database stuff that probably has an overload that accepts `<T>`
}
// Or:
const query = <T,>(sql:string, params:object):Array<T> => {
//Database stuff that probably has an overload that accepts `<T>`
}
Called like:
await query<MyDataRow>('SELECT ...');
CodePudding user response:
You have to use generics
const query = <T>(sql: string, params: Object[]): T[] => {
return []
}
But function can return empty array. In this case you can check cnt
property like this
const result = await query('SELECT count(*) as cnt from Table id=?',[2])
return result[0]?.cnt