Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all exports of a module in the same file programatically in Typescript/Javascript ES6

I want to iterate over all module exports to extract their types.

I assume that during compile time this information would be available

export const a = 123;
export const b = 321;

// Is there any way to do something like this in typescript/javascript es6?
console.log(module.exports)
// { a: 123, b: 321 }

Edit: I would like to share the solution to the issue I mentioned on the first line.

Thanks for the answer, but it appears I was wrong to restrict it to a single file altogether. I created a separate types.ts and used 'utility-types' library for the relevant type manipulations

import { ValuesType } from 'utility-types';
import * as myModue from './myModule';

export IMyModuleType = ValuesType<typeof myModue>;

And then just imported the type with the new 3.8 syntax

import type { IMyModuleType } from './types';
//...
like image 889
Grigory Bogush Avatar asked Oct 24 '25 18:10

Grigory Bogush


1 Answers

You can play with the typescript Compiler API. It gives you all the info you need

import * as ts from "typescript";

function compile(fileNames: string[], options: ts.CompilerOptions): void {
  let program = ts.createProgram(fileNames, options);
  let emitResult = program.emit();

  console.log(program)
}

compile(['your-filename.ts'], {
  noEmitOnError: true,
  noImplicitAny: true,
  target: ts.ScriptTarget.ES5,
  module: ts.ModuleKind.CommonJS
});
like image 106
Guilhermevrs Avatar answered Oct 26 '25 09:10

Guilhermevrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!