[英]How to create a definition typescript file with a default export and functions inside?
我必須使用內部庫對用戶進行身份驗證,但是現在我必須在打字稿項目中使用此庫,因此我試圖創建其定義文件(.d.ts),但是我都沒有嘗試過。
通常我會這樣使用它:
import login from 'int-login';
...
login.requestAuth('admin', 'admin').then(user => console.log(user));
所以我試圖創建這樣的定義文件:
declare module 'int-login' {
export default class login {
requestAuth(username: string, password: string);
}
}
但這是返回的錯誤:類型'typeof login'不存在屬性'requestAuth'。 我試圖將函數移出“登錄”類,但隨后它說登錄不存在,因為我將其導入到打字稿文件中。
定義文件的格式取決於定義文件是與庫一起打包還是位於依賴庫的項目中。 如果要使用庫打包定義,請刪除declare module
包裝器,並確保庫package.json
文件中包含"types"
屬性以及定義文件的位置。
看起來您希望requestAuth
返回一個Promise,因此您需要在定義中指出返回類型。
定義文件應具有此內容。
export interface User {
// list appropriate property types here
}
export default class login {
requestAuth(username: string, password: string): Promise<User>;
}
另一方面,如果定義文件位於依賴於int-login的項目中(可能位於types/
文件夾中),或者位於單獨的@types/int-login
包中,那么您確實需要declare module
包裝。 您還需要確保tsconfig.json
的"include"
配置值包含了定義文件。 在這種情況下,定義文件將如下所示:
declare module "int-login" {
export interface User {
// list appropriate property types here
}
export default class login {
requestAuth(username: string, password: string): Promise<User>;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.