Skip to content

fix(typings): allow indexing Types with FieldPacket.type - #4582

Open
DylanMerigaud wants to merge 1 commit into
sidorares:masterfrom
DylanMerigaud:fix/3279-types-number-index
Open

DylanMerigaud wants to merge 1 commit into
sidorares:masterfrom
DylanMerigaud:fix/3279-types-number-index

Conversation

@DylanMerigaud

Copy link
Copy Markdown

Fixes #3279

FieldPacket.type and columnType are typed as number, but Types only declares its literal keys, so looking up a column's type name does not compile under noImplicitAny:

import mysql from 'mysql2';

const typeName = (field: mysql.FieldPacket) =>
  field.type === undefined ? undefined : mysql.Types[field.type];
// error TS7053: Element implicitly has an 'any' type because expression of
// type 'number' can't be used to index type 'Types'.

It is not ESM only: with module: NodeNext, a CommonJS package and an ESM package get the same error.

This adds [key: number]: string to Types, which is what TypeScript gives the reverse mapping of a numeric enum. The declared keys keep their types (Types.BLOB is still number, Types[0x00] still string), and with noUncheckedIndexedAccess an arbitrary code reads as string | undefined. Two things get looser. A code that is not in the map, such as Types[0x11], now compiles as string instead of failing, although it is undefined at runtime. And keyof Types now includes number instead of the 29 listed codes, so a union of codes derived from it becomes number, and an exhaustive switch over that union no longer compiles. I kept string rather than string | undefined because TypeCastField.type already assumes the same: the parsers read it from this map, and it is typed without undefined.

The new lines in test/tsc-build/{mysql,promise}/constants/Types.test.ts fail on master with TS7053 and pass here, and the @ts-expect-error line fails if the lookup ever widens to any. npm run lint, npm run typecheck, npm run test:build and npm test (MySQL 8.3) pass locally, and the declaration also compiles on TypeScript 4.7, 4.9, 5.0, 5.4 and 5.9.

This change was prepared with AI assistance (Claude).

FieldPacket.type and columnType are numbers, so mysql.Types[field.type]
failed with TS7053 under noImplicitAny.

Fixes sidorares#3279

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

This comment was marked as off-topic.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TypeError: FieldPacket type can't be used to access mysql.Types

2 participants