When using TypeScript 4.4.3, I am looking to specify the types of function parameters for a function that returns a generic. However, TypeScript seems to be treating the parameters as any
when working with functions that involve generics.
Here's a simplified example that demonstrates this issue: if this code is pasted into the TS Playground, a warning will show up regarding the input parameter being of type "any"...
type GenericResult = <T>(input: number) => T
export const returnWhatever: GenericResult = <T>(input) => <T> input
Should the parameter's type declaration in the first line be disregarded?
My real-world scenario is as follows...
import type { QueryResult } from 'pg'
import pg from 'pg'
const pgNativePool = new pg.native.Pool({
max: 10,
connectionString: import.meta.env.VITE_DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
})
type AcceptableParams = number | string | boolean
type PostgresQueryResult = (sql: string, params?: AcceptableParams[]) => Promise<QueryResult<any>>
const query: PostgresQueryResult = (sql, params?) => pgNativePool.query(sql, params)
type GetOneResult = <T>(sql: string, id: number | string) => Promise<T>
const getOne: GetOneResult = async <T>(sql, id) => {
const { rows } = await query(sql, [id])
return <T> rows[0]
}
const user = await getOne<User>('SELECT * FROM users WHERE id = $1;', 33)
// returns a User
In the above example, the sql parameter should always be a string, while id can be either a number or a string.
Even though the return value of the function is determined when the function is called, it would be beneficial to be able to type the parameters of the function since that information is known.
Is this achievable?