Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union all imported types

Tags:

typescript

Is there way to union all imported types from module? Like this

import * as types from "./types";

type Union_ = Union<types> // type1 | type2 | ...

I also know that only types and interfaces will be exported from this file.

like image 455
Supremus Avatar asked Nov 14 '25 21:11

Supremus


2 Answers

No it's not possible.
You have to do named imports.
One possible solution is to union all the types in your types.ts file and export it from there and use it in this file.

like image 199
Mahdi Ghajary Avatar answered Nov 17 '25 12:11

Mahdi Ghajary


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

There are a couple of ways that you can do this, but ideally you'd avoid wildcard imports in anything that will be bundled into your build.

What I ended up not going with:

import * as types from './types';

const typeValues = Object.values(types);
export type FooConst = typeValues[number];

The other idea I was working on would involve compilation to generate a union type based on the imports. something like tsc

like image 26
kvanost Avatar answered Nov 17 '25 12:11

kvanost