Как установить модель типа n pouchdb upsert? - PullRequest
0 голосов
/ 13 ноября 2018

Кажется, я не могу найти решение по этому вопросу. используя upsert на pouchdb я получаю TS2345 и или TS2339.

Я пытался использовать его как htis.

db.upsert('id', doc => {
  doc.p = 'sample';
  return doc;
});

но на doc.p я получаю TS2339 Property 'p' does not exist on type '{} | IdMeta'

и основано на pouchdb-upsert / index.d.ts, оно имеет это определение

upsert<Model>(docId: Core.DocumentId, diffFun: UpsertDiffCallback<Content & Model>): Promise<UpsertResponse>;

Итак, я попробовал это

db.upsert<{ p: string }>('id', doc => {
  doc.p = 'sample';
  return doc;
});

но теперь я получаю TS2345 и TS2339. вот ошибка

Argument of type '(doc: {} | Document<{ p: string; }>) => {} | Document<{ p: string; }>' is not assignable to parameter of type 'UpsertDiffCallback<{ p: string; }>'.
   Type '{} | Document<{ p: string; }>' is not assignable to type 'false | "" | 0 | ({ p: string; } & Partial<IdMeta>) | null | undefined'.
     Type '{}' is not assignable to type 'false | "" | 0 | ({ p: string; } & Partial<IdMeta>) | null | undefined'.
       Type '{}' is not assignable to type '{ p: string; } & Partial<IdMeta>'.
         Type '{}' is not assignable to type '{ p: string; }'.
           Property 'p' is missing in type '{}'. (typescript-tide)

Кто-нибудь? пожалуйста, спасибо.

Обновление

Когда я проверяю это так:

  public test() {
    new PouchDB('test').upsert<{ p: string }>('id', doc => {
      doc.p = 'test string';
      return doc;
    })
  }

Я получаю это:

Argument of type '(doc: Partial<Document<{ p: string; }>>) => Partial<Document<{ p: string; }>>' is not assignable to parameter of type 'UpsertDiffCallback<{ p: string; }>'.
   Type 'Partial<Document<{ p: string;; }>>' is not assignable to type 'false | "" | 0 | ({ p: string; } & Partial<IdMeta>) | null | undefined'.
     Type 'Partial<Document<{ p: string; }>>' is not assignable to type '{ p: string; } & Partial<IdMeta>'.
       Type 'Partial<Document<{ p: string; }>>' is not assignable to type '{ p: string; }'.
         Types of property 'p' are incompatible.
           Type 'string | undefined' is not assignable to type 'string'.
             Type 'undefined' is not assignable to type 'string'. (typescript-tide)

Пока я делаю это так:

  public test2() {
    new PouchDB<{ p: string }>('test').upsert('id', doc => {
      doc.p = 'test string';
      return doc;
    })
  }

Я получаю это:

Argument of type '(doc: Partial<Document<{ p: string; }>>) => Partial<Document<{ p: string; }>>' is not assignable to parameter of type 'UpsertDiffCallback<{ p: string; } & Partial<Document<{ p: string; }>>>'.
   Type 'Partial<Document<{ p: string; }>>' is not assignable to type 'false | "" | 0 | ({ p: string; } & Partial<Document<{ p: string; }>> & Partial<IdMeta>) | null | ...'.
     Type 'Partial<Document<{ p: string; }>>' is not assignable to type '{ p: string; } & Partial<Document<{ p: string; }>> & Partial<IdMeta>'.
       Type 'Partial<Document<{ p: string; }>>' is not assignable to type '{ p: string; }'.
         Types of property 'p' are incompatible.
           Type 'string | undefined' is not assignable to type 'string'.
             Type 'undefined' is not assignable to type 'string'. (typescript-tide)

1 Ответ

0 голосов
/ 13 ноября 2018

Корень проблемы в том, что ваш diffFun получает аргумент {}, если документ не существует и этот тип не имеет полей.Я отправил запрос на получение в DefiniteTyped, чтобы изменить тип аргумента на Partial<Core.Document<Content & Model>>, что будет более полезным, поскольку позволит вам назначать поля.(См. этот ответ о возможных способах использования моих измененных объявлений до объединения запроса на извлечение.)

Однако, если вы используете тип документа с обязательными полями, такими как { p: string },вы все равно не сможете вернуть doc без подтверждения типа, потому что TypeScript все еще думает, что doc имеет только необязательное свойство.Вы можете указать тип документа как { p?: string }, и тогда ваш код будет скомпилирован без ошибок.Но если вы ожидаете, что все документы в базе данных будут иметь свойство p, вероятно, лучше использовать { p: string }, и каждый diffFun либо использует утверждение типа, либо возвращает новый объект, так что вы напоминаете, чтовам нужно инициализировать все необходимые свойства в случае, если документ не существует.

...