简体   繁体   English

如何创建带有默认导出和功能的定义打字稿文件?

[英]How to create a definition typescript file with a default export and functions inside?

I have to use an internal library to authenticate the users, but now I have to use this lib in a typescript project, so I'm trying to create its definition file (.d.ts), but none of I've tried works. 我必须使用内部库对用户进行身份验证,但是现在我必须在打字稿项目中使用此库,因此我试图创建其定义文件(.d.ts),但是我都没有尝试过。

Normally I would use it like this: 通常我会这样使用它:

import login from 'int-login';
...
login.requestAuth('admin', 'admin').then(user => console.log(user));

So I tried to create the definition file like this: 所以我试图创建这样的定义文件:

declare module 'int-login' {
    export default class login {
        requestAuth(username: string, password: string);
    }
}

But this is the error returned: Property 'requestAuth' does not exist on type 'typeof login'. 但这是返回的错误:类型'typeof login'不存在属性'requestAuth'。 I tried to move the function out of the class 'login', but then it says login doesn't exists whe I import it in my typescript file. 我试图将函数移出“登录”类,但随后它说登录不存在,因为我将其导入到打字稿文件中。

The format for the definition file depends on whether the definition file is packaged with the library, or is in the project that depends on the library. 定义文件的格式取决于定义文件是与库一起打包还是位于依赖库的项目中。 If you want to package the definitions with the library then remove the declare module wrapper, and make sure that there is a "types" property in the library package.json file with the location of the definition file. 如果要使用库打包定义,请删除declare module包装器,并确保库package.json文件中包含"types"属性以及定义文件的位置。

It looks like you expect requestAuth to return a promise, so you need to indicate the return type in the definitions. 看起来您希望requestAuth返回一个Promise,因此您需要在定义中指出返回类型。

The definition file should have this content. 定义文件应具有此内容。

export interface User {
    // list appropriate property types here
}

export default class login {
    requestAuth(username: string, password: string): Promise<User>;
}

On the other hand if the definition file is in the project that depends on int-login (perhaps in a types/ folder), or in a separate @types/int-login package, then you do need the declare module wrapping. 另一方面,如果定义文件位于依赖于int-login的项目中(可能位于types/文件夹中),或者位于单独的@types/int-login包中,那么您确实需要declare module包装。 You also need to make sure that the definition file is included by the "include" configuration value in tsconfig.json . 您还需要确保tsconfig.json"include"配置值包含了定义文件。 In that case the definition file would look like this: 在这种情况下,定义文件将如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM