1

So, I have a file structure like this:

|---- foo.ts
|---- bar.ts
|- index.ts

Both foo.ts and bar.ts export a Data interface. What I'd want is to basically create a union type out of the 2 Data interfaces exported from foo and bar. Ideally, this should also be future proof. I.e. if I add a third file at the same level of foo and bar, that file will also export a Data interface and that should be included in the union type too.

I was wondering if there was a way of doing this without performing type generation from a JSON schema or something at "compile" time and the programmatic creation of the union type itself from this.

Federico Luzzi
  • 128
  • 1
  • 10
  • Are you asking if you can generate the type based purely on the presence of the file, and without importing anything from that explicitly? Because I don't think that's possible. – Alex Wayne Apr 11 '22 at 17:34
  • Yeah that would kinda be the question. I'm pretty damn doubtful it can be done too, but wanted to be sure since I'm not a Typescript expert. – Federico Luzzi Apr 11 '22 at 19:12

1 Answers1

0

I had a similar question: Is there a good way to generate types by importing all variables from a file in typescript

I did figure out a way to do this, but it's definitely not pretty:

// index.ts
import * as foo from './foo.ts';
import * as bar from './bar.ts';

const foos = Object.values(foo);
const bars = Object.values(bar);
const foosAndBars = [...foos, ...bars];
export type Foobars = typeof foosAndBars[number];
kvanost
  • 11
  • 2