[英]How to use imported libraries as a type property
I'd like to declare a type, and set one of its properties as an imported library.我想声明一个类型,并将其属性之一设置为导入库。
The ultimate goal of this is to have the Dependencies of my platform defined in a single place.这样做的最终目标是在一个地方定义我的平台的依赖项。
Simplifying, I have something like this:简化,我有这样的事情:
import * as crypto from 'crypto';
export type Dependencies = {
... (Some dependencies)...
crypto: crypto;
... (Some more dependencies)...
}
function ({ crypto }: Dependencies, length: number) {
return crypto
.createHmac('sha256', Math.random() * 10 ** length + '')
.digest('hex')
.substring(0, length);
}
But when defining the type I get Cannot use namespace 'crypto' as a type.ts(2709)
但是在定义我得到的类型时,
Cannot use namespace 'crypto' as a type.ts(2709)
I've tried using interface instead of type, but ran into the same problem.我尝试使用接口而不是类型,但遇到了同样的问题。
Bottom line, the question is: Is there any way I can define that X property (or method) of either an interface or a type, should be that of a library?归根结底,问题是:有什么方法可以定义接口或类型的 X 属性(或方法)应该是库的属性(或方法)吗?
Thanks!谢谢!
Try:尝试:
type CryptoModule = typeof import("crypto");
Dumb example:愚蠢的例子:
/**
* @param {CryptoModule} arg
*/
const foo = (arg) => 42;
foo("hi"); // Argument of type '"hi"' is not assignable to parameter of type 'typeof import("crypto")'.ts(2345)
foo(crypto); // fine
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.