简体   繁体   中英

TypeScript: what to do when return type of library function is unknown

I am new to TypeScript and I don't know what type to use when I am calling library functions / methods. For example I am using the headless chrome module in my Node.js project.

import puppeteer = require("puppeteer");

async function launchBrowser () {
    const browser = await puppeteer.launch();

    return browser;
}

// In this case I do not know the return type of the launch method. What should I do?

async function launchBrowser (): Promise<any> {
    const browser: any = await puppeteer.launch();

    return browser;
}

Should I use any or leave it without type?

Assuming you cannot find typings for your library, at the very least I would have the function return a promise of something, since you know it is async.

Newer versions of TypeScript introduced the unknown type:

async function launchBrowser (): Promise<unknown>

But you can also return a promise of any :

async function launchBrowser (): Promise<any>

Check out the docs for the new unknown type: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html

Before using unknown or any , I would try seeing if the types for your library exist in npm @ types to see if the type information can be located there.

It looks like there are types for puppeteer:

npm install --save @types/puppeteer

As far as what you should do, that's more up to you. If hypothetically no types were available, then you could be kind of stuck. You could create your own typings file and merge it via Typescript's Declaration Merging feature. However, I would advise against that because

A. You'd have to update your typings file everytime you updated the library, which is a pain

B. You could end up really confusing yourself if you aren't completely correct about the types that the library returns

I would probably just leave it at unknown or any to make things easier.

Edit: The better answer is to follow @Frank Modica's answer and wrap the result in a Promise, such as Promise<any> or Promise<unknown> . This provides at least some intellisense info and is much better than simply defining it as any or unknown as I had previously stated.

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