Back

How To Extend Document Type On Typescript?

  • 0
  • Databases
  • Web
pank 🇳🇵
8 Feb, 2025, 06:46

can we extend Document to infer types of attributes while retrieving documents on Typescript? What's the preferred way? Because DocumentList<Document> doesn't include attributes and currently I have to go with any as workaround.

TL;DR
To extend the type of `Document` with the attributes queried using `Query.select()` in Typescript, developers may need to create custom interfaces like `Stat` and use a mapping function like `documents.map((doc) => ...)`. Prefetching types with a library could also be an option. However, the dynamic nature of the `data` property may complicate this process. Remember that `Document.data` typically requires manual type handling.
Darshan Pandya
8 Feb, 2025, 06:49

what's the usecase? iirc, the main structure would be in Document.data, DocumentList is just a type that holds a total: number & the list of documents. If you mean infer the return type from the sdk return types, I don't think so.

Darshan Pandya
8 Feb, 2025, 06:49

you can always play around with extended types though.

Darshan Pandya
8 Feb, 2025, 06:50

you could do some sort of documents.map((doc) => ...).

D5
8 Feb, 2025, 06:50

From what I understand, instead of doing document.data["Attribute"] Doing document.data.attribute so it gets completed automatically

Darshan Pandya
8 Feb, 2025, 06:51

i see, but the type won't exist due to data's dynamic nature. but iirc, there was a library by a community member that would pre-fetch the types. should be in #🛠│tools ig.

pank 🇳🇵
8 Feb, 2025, 06:51

Maybe I didn't explained it well enough. Could be something totally related to ts only. Let me give bit more context. Give me a while

pank 🇳🇵
8 Feb, 2025, 06:56

Following is a function I'm using to retrieve some aatribute from the documents.

TypeScript
  const statsData = await databases.listDocuments(
    APPWRITE_DB_ID,
    APPWRITE_FILES_COUNTS_COL_ID,
    [Query.select(["year", "month", "count"])]
  );

The return type right now is statsData is Models.DocumentList<Models.Document>. The Models.Document type has metadata related values mostly. like $id, $createdAt

Can I extend the type of Document such that along with the metadata, I can also get type of the attributes I've queried with Query.select()?

Along with the existing Document type, I also want to infer following when I access statsData

TypeScript
  interface Stat {
    year: number, 
    month: number, 
    count: number
  }
pank 🇳🇵
8 Feb, 2025, 06:57

@Darshan Pandya @D5

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more