webnator
webnator

Reputation: 13

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)

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?

Thanks!

Upvotes: 1

Views: 141

Answers (1)

Manu Artero
Manu Artero

Reputation: 10293

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

Upvotes: 1

Related Questions