Skip to content

Conversation

@stevescruz
Copy link
Contributor

@stevescruz stevescruz commented Feb 24, 2023

Description

Small change, but some developers enjoy working with generics over the any type when using TypeScript.

Added Generics type annotations for the following methods:

  • Statement.get
  • Statement.all
  • Statement.each
  • Database.get
  • Database.all
  • Database.each

Backwards Compatibility

This will not break existing TypeScript code. It will still be possible to directly add type annotations to the row/rows.

Examples:

Take into consideration the following TypeScript code:

import sqlite3 from "sqlite3";

interface IUser {
    id: string;
    name: string;
    email: string;
}

const db = new sqlite3.Database("./test.db");
const createTableQuery = `CREATE TABLE IF NOT EXISTS users (
    id TEXT PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,
    email TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;

How type annotations currently works:
NOTE: this will still work after the code changes.

const query = "SELECT * FROM users";
db.all(query, [], (err, rows: IUser[]) => {
    if (err) {
        console.error(err.message);
    } else {
        console.log(rows[1].email);
    }
});

Now you will be able to:

const query = "SELECT * FROM users";
db.all<IUser>(query, [], (err, rows) => {
    if (err) {
        console.error(err.message);
    } else {
        console.log(rows[1].email);
    }
});

…ent methods

-For get method callback's row
-For all method callback's rows
-For each method callback's row
…se methods

-For get method callback's row
-For all method callback's rows
-For each method callback's row
@stevescruz stevescruz changed the title Add generic type definitions for Statement and Database get/all/each methods callback rows Add generic type annotations for Statement and Database get/all/each methods callback rows Feb 24, 2023
@stevescruz
Copy link
Contributor Author

@daniellockyer thanks for running the CI pipeline.
We can add the "types" label to this PR.

@daniellockyer daniellockyer merged commit 46da1ab into TryGhost:master Mar 13, 2023
@daniellockyer
Copy link
Contributor

@stevescruz Nice, thanks!

@stevescruz stevescruz deleted the stevescruz/add-generic-type-definitions-for-callback-rows branch March 22, 2023 06:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants