[英]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. 我是TypeScript的新手,我不知道在调用库函数/方法时要使用什么类型。 For example I am using the headless chrome module in my Node.js project.
例如,我在Node.js项目中使用无头chrome模块。
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: 较新版本的TypeScript引入了
unknown
类型:
async function launchBrowser (): Promise<unknown>
But you can also return a promise of any
: 但你也可以回复
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 查看新
unknown
类型的文档: 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. 在使用
unknown
或any
之前,我会尝试查看您的库的类型是否存在于npm @ types
以查看类型信息是否可以位于那里。
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.
您可以创建自己的打字文件,并通过Typescript的声明合并功能将其合并。 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 B.如果你对图书馆返回的类型不完全正确,你最终可能会感到困惑
I would probably just leave it at unknown
or any
to make things easier. 我可能会把它留在
unknown
或any
使事情变得更容易。
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>
. 编辑:更好的答案是遵循@Frank Modica的答案并将结果包装在Promise中,例如
Promise<any>
或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. 这提供了至少一些智能感知信息,并且比简单地将其定义为我之前所述的
any
或unknown
要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.