Skip to content

fix(types): type pg Client as the constructor (typeof Pg.Client)#219

Open
imharjot wants to merge 1 commit into
fastify:mainfrom
imharjot:fix/pg-client-constructor-type
Open

fix(types): type pg Client as the constructor (typeof Pg.Client)#219
imharjot wants to merge 1 commit into
fastify:mainfrom
imharjot:fix/pg-client-constructor-type

Conversation

@imharjot

Copy link
Copy Markdown

What

Change the Client member of the public PostgresDb type from Pg.Client to typeof Pg.Client.

Why

At runtime the plugin assigns the pg Client class (the constructor) to app.pg.Client:

// index.js
const db = {
  connect: pool.connect.bind(pool),
  pool,
  Client: pg.Client, // <- the constructor/class, not an instance
  query: pool.query.bind(pool),
  transact: transact.bind(pool)
}

But the type declaration described it as an instance:

// index.d.ts (before)
export type PostgresDb = {
  pool: Pg.Pool;
  Client: Pg.Client; // instance type
  ...
}

Since @types/pg declares export class Client, Pg.Client is the instance type and typeof Pg.Client is the constructor type. As a result, instantiating a one-off client via the decorator — new app.pg.Client({ connectionString }) — failed to type-check:

error TS2351: This expression is not constructable.
  Type 'Client' has no construct signatures.

even though it works at runtime.

Change

// index.d.ts (after)
Client: typeof Pg.Client;

and the corresponding type test now asserts the constructor type:

expect(app.pg.Client).type.toBe<typeof Client>()

Testing

  • npm run test:typescript (tstyche): all 4 type-test files pass, 13/13 assertions pass.
  • npm run lint: clean.
  • Verified new app.pg.Client({ connectionString }) now type-checks (no TS2351), and reproduced the failure before the change.

This is a type-only change with no runtime impact, so unit-test coverage (c8 --100) is unaffected.

The plugin assigns `pg.Client` (the class) to `app.pg.Client` at runtime,
but the `PostgresDb` type declared it as `Pg.Client` (an instance). This made
`new app.pg.Client(...)` fail to type-check with TS2351 "This expression is not
constructable" even though it works at runtime.

Type the member as `typeof Pg.Client` so it reflects the constructor, and update
the type test to assert against `typeof Client`.

Signed-off-by: Harjot Singh <harjotsrance@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants