Jonathan Verrecchia
Jonathan Verrecchia

Reputation: 45

How to type unknown exports that will be imported with named imports in TypeScript?

I am making an NPM package that transforms process.env and exports the transformed env for convenient use.

The module:

const transformedEnv = transform(process.env)

module.exports = transformedEnv

Using it (in a Babel / TS codebase):

import { SOME_ENV_VAR } from 'transform-env'

My module works as expected but I would like to provide a TypeScript definition.

The problem is that I cannot know what properties the env will have, so I cannot use named exports, and I cannot find a way to type "unknown" exports. I currently get the following TS2305 error, which makes complete sense, since I do not export anything with named exports:

error TS2305: Module '"transform-env"' has no exported member 'SOME_ENV_VAR'.

Is there a way type those unknown named exports (something like using a * in the exports?).

And if not, is there a way to bypass this error on the package-side instead of using a @ts-ignore on the consumer module side?

Upvotes: 0

Views: 1327

Answers (2)

Jonathan Verrecchia
Jonathan Verrecchia

Reputation: 45

I've been able to bypass the type checking of my module entirely by adding an index.d.ts next to the index.js file of my package, containing:

declare module 'transform-env'

This is definitely not ideal, I'd rather have real type definitions, but at least consumer projects can use import { SOME_ENV_VAR } from 'transform-env' without TypeScript blocking the compilation.

Still looking for better solutions.

Upvotes: 1

Aviso
Aviso

Reputation: 695

You can use

import * as anyName from 'transform-env'

Upvotes: 0

Related Questions