簡體   English   中英

在 mongoose .d.ts 中分配自定義方法,以便我可以在打字稿中使用 mongoose 的任何地方使用它們

[英]Assign custom methods in mongoose .d.ts so I can use them anywhere with mongoose in typescript

我正在嘗試在 mongoose Api hooks 中創建一個自定義函數,但該函數未定義,因為它尚未聲明。 我創建了 index.d.ts 單獨的文件,但不知道如何添加。

const exec = mongoose.Query.prototype.exec;

mongoose.Query.prototype.cache = function (options:ICacheOptions = {}) {
  this.useCache = true;
  this.hashKey = JSON.stringify(options.key || "");
  return this;
}

鏈接 :: cache.ts

錯誤是: “查詢”類型上不存在屬性“緩存”。 您指的是 'catch' 嗎?

我嘗試過的:我創建了 .d.ts 文件並嘗試聲明它們。

declare module 'mongoose' {
  interface DocumentQuery<T,  DocType extends import("mongoose").Document, QueryHelpers = {}>{
    mongooseCollection: {
      name: any;
    };
    cache():DocumentQuery<T[], Document> & QueryHelpers;
    useCache: boolean;
    hashKey: string;

  }
}

鏈接:: index.d.ts

我的錯誤是 ::

src/lib/services/cache.ts(16,26): error TS2551: Property 'cache' does not exist on type 'Query<any>'. Did you mean 'catch'?
src/lib/services/cache.ts(17,8): error TS2339: Property 'useCache' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(18,8): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(25,12): error TS2339: Property 'useCache' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(30,41): error TS2339: Property 'mongooseCollection' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(33,52): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(45,22): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.
src/lib/services/cache.ts(46,24): error TS2339: Property 'hashKey' does not exist on type 'Query<any>'.

我想以某種方式解決這個問題,還想知道如果它們是類,我如何在 .d.ts 中擴展一些屬性。 提前致謝。

你的增強確實有效。 它需要放置在您已配置 TypeScript 以查找源文件的某個位置。 類型定義的declare module樣式稱為“環境聲明”,這意味着您不必將其放在任何特定目錄或文件中。 它甚至可以在一個普通的.ts文件中。 最容易做的事情是把在申報cache.ts ,在那里你將相同的文件mongoose.Query.prototype.cache

編輯:我忘了解決你關於增加課程的具體問題。 正如您所猜測的,您可以使用interface關鍵字來擴充類。 這是因為在 TypeScript 中定義一個類有兩件事:它定義一個值(當你調用時調用的構造函數,例如new DocumentQuery ),以及一個真正是接口的類實例的類型。 值和類型都具有相同的名稱。 因為類的類型部分是一個接口,所以您可以像任何其他接口一樣對其進行擴充。

因此,在這種情況下,您增加了DocumentQuery類型,它是Query的超類,但您將cache方法分配給Query原型。 這是有效的,因為Query擴展了DocumentQuery ,因此當您聲明DocumentQuery現在具有cache方法時,TypeScript 假定子類,包括Query ,具有相同的方法。 這確實導致了一個差異:TypeScript 現在假設DocumentQuery實例具有cache方法,但您只是為Query真正定義了該方法。 更改您的類型聲明以增加Query而不是DocumentQuery ,或者將方法實現分配給DocumentQuery.prototype而不是Query.prototype會更准確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM