実現したいこと
nodejsでmysql2を使っていて以下のクエリを実行したときに返ってくるものの処理の仕方が知りたいです。この変数の型がなんなのかいまいちつかめてないです。
該当のソースコード
js
1const [row1] = await connection.query(`select count(*) from accounts where email = '${req.body.email}'`); 2console.log(row1);
試したこと
とりあえず返ってくるデータを表示させてみたいんですがこうなりました。この中の数字だけを取得したいです。
[ { 'count(*)': 0 } ]
console.log(row1["count(*)"]);
も当然エラーでダメでした。
補足情報(FW/ツールのバージョンなど)
配列のように見えたので表示させましたがだめでした。うまくいかなかったのでこうして質問をしたのですが。
> 当然エラーでダメでした。
どのようなエラーが出たのですか?
```
TSError: ⨯ Unable to compile TypeScript:
index.ts:49:22 - error TS7053: Element implicitly has an 'any' type because expression of type '"count(*)"' can't be used to index type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader'.
Property 'count(*)' does not exist on type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader'.
49 logger.debug(row1["count(*)"]);
```
です。予想していた型とはそもそもが違っていたのでよくわからないです
row1 はオブジェクトの配列なので、row1[0]["count(*)"] かなぁ。
```
^
TSError: ⨯ Unable to compile TypeScript:
index.ts:49:22 - error TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader'.
Property '0' does not exist on type 'RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader'.
49 logger.debug(row1[0]["count(*)"]);
~~~~~~~
at createTSError (/app/api/node_modules/ts-node/src/index.ts:859:12)
at reportTSError (/app/api/node_modules/ts-node/src/index.ts:863:19)
at getOutput (/app/api/node_modules/ts-node/src/index.ts:1077:36)
at Object.compile (/app/api/node_modules/ts-node/src/index.ts:1433:41)
at Module.m._compile (/app/api/node_modules/ts-node/src/index.ts:1617:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
at Object.require.extensions.<computed> [as .ts] (/app/api/node_modules/ts-node/src/index.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1027:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
diagnosticCodes: [ 7053 ]
}
```
そもそも動かせてくれません。なんの型なのかがよくわからない....
> なんの型なのかがよくわからない....
とりあえず(row1 as any)として、型チェックを殺してみてはどうでしょうか。
[row1]: any
としたら行けました。ありがとうございます

回答2件
あなたの回答
tips
プレビュー