1

I am trying to use CouchDB, and it's nano npm library that has typescript types. I managed to insert documents, however I don't know how to type a response document. Here is the function that gets the data:

export const getAlarms = async (): Promise<IAlarm[]> => {
  const list = await db.list({ include_docs: true });
  const alarms = list.rows.map(alarm => {
    if (alarm.doc) {
      return Alarm.from(alarm.doc);}
    });
  return alarms;
};

Typescript throws an error at alarm.doc:

[ts] Argument of type 'Document' is not assignable to parameter of type 'IAlarm'. Property 'name' is missing in type 'Document'.

I cannot find anywhere what to do at this point, how can I tell TS that the return document from this call is of my type and not a simple Document?

Edit: Just managed to fix it using alarm.doc as IAlarm - how good of an approach is it?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Vlives
  • 405
  • 1
  • 4
  • 8
  • It's fine. Typescript debugger is there just to make your life easy. You can define alarm type wherever you want. – itdoesntwork Aug 27 '18 at 11:46
  • 4
    There may be another way to do this. Looking at the [declarations](https://github.com/apache/couchdb-nano/blob/master/lib/nano.d.ts), it looks like the `use` function takes a type argument `D` for the document type and produces a `DocumentScope`. Are you getting `db` by calling `use`? If so, call `use`. – Matt McCutchen Aug 27 '18 at 22:36
  • 1
    @MattMcCutchen You are right, I can call `use` with the supplied type! Didn't know that this was a feature. You can post it as an answer and I will accept it. – Vlives Aug 29 '18 at 11:31
  • Where was `alarm as alarm.doc` used exactly in this example? (sorry for dredging up old qn, but there's not many with answers on this topic) – Alex McAllister Jan 22 '20 at 15:17

0 Answers0