I'm exporting all my database tables and their types. In the end, I have the table names and the data types inside them.
For example:
type commentsType { ... }
type notificationsType { ... }
type projectsType { ... }
I also have an array of the collection names:
comments, notifications, projects...
Since the fetch calls are similar for fetching data, I'm trying to create a function in TypeScript that can also infer the type.
In JavaScript, I wrote something like this:
const db = {};
for (collection in collections) {
db[collection].getList = fetch...;
db[collection].getOne = fetch...;
}
The dream is to write this in TypeScript so that it also knows what it returns. For example:
db["comments"].getList = <commentsType[]>;
db["projects"].getList = <projectsType[]>;
I'm trying to make this generated automatically, instead of having to manually update it every time the database changes.|
the closest i got with AI was this .. but the compiler doesn't like it, and it doesn't work
type Collection = {
name: string;
};
const collections2: Collection[] = [
{ name: "comments" },
{ name: "notes" },
];
type DbFunctions = {
[K in Collection['name']]: {
getList: () => allTypes[`${K}Type`][];
};
};
export const dbFunctions: DbFunctions = Object.fromEntries(
collections2.map(({ name }) => [
name,
{
getList: (): allTypes[`${name}Type`][] => {
// Implement the getList function here
return [];
},
},
])
);