简体   繁体   中英

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.

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'. 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.

It looks like you expect requestAuth to return a promise, so you need to indicate the return type in the definitions.

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. You also need to make sure that the definition file is included by the "include" configuration value in tsconfig.json . 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>;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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