#Change remove keys in function return type based on input argument

5 messages · Page 1 of 1 (latest)

gritty shoal
#

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

shadow berry
#

you need to use generics

#

minimal example

gusty wyvernBOT
#
xibread#0

Preview:```ts
interface Foo {
a: string
b: string
c: string
d: string
}

declare function select<K extends keyof Foo>(id: number, columns: K[]): Pick<Foo, K>;

const foo = select(42, ["a"])
foo.```

gritty shoal
#

ohhh it seems so obvious now thank so very much