I have an SQLite3 database that i can query using some "helper methods" . These methods can take ,whatever arguments are required for the query, plus an optionam column argument used to retrieve only the information i need.
What i'd like to do is to "limit the keys" on the return type of these helper methods based on the column argument. I searched a bit on SO and the TypeScript docs i came with that:
import sqlite from 'better-sqlite3';
interface GuildEvent {
id: number,
title: string,
description: string,
date: string,
message_id: string,
...
}
export default class Database extends sqlite {
constructor(...) {...}
selectEvent(id: number, columns: (keyof GuildEvent)[] = []) {
const formattedColumns = columns.join(', ') || '*';
const rawEvent = this.query(`SELECT ${formattedColumns} FROM guild_events WHERE id = ${id}`);
return this.revive(rawEvent) as Pick<GuildEvent, typeof columns[number]>
}
}
But it doesn't work, the other properties are still visible:
const eventId = 42;
const event = database.selectEvent(eventId, ['message_id']);
console.log(event.title); // no error
Here are some things i found during my researches that may be useful:
https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
https://stackoverflow.com/questions/52085454/typescript-define-a-union-type-from-an-array-of-strings
https://stackoverflow.com/a/68840998
I can't be the first person coming across this, but my searches have not turned up any useful leads yet. Would greatly appreciate some expert TypeScript advice.
Say I have an array:
const fruits ...
If I do not want the value of a parameter change within a function scope, is there any way to annotate that with Typescript?
I've tried:
function walk(const fileName: string): string[] {
// -----...
Types which are globally included in TypeScript