It appears that your goal is to implement union types
. To define union types in TypeScript, you can follow the example below:
Scenario 1: Define individual types in a separate module and use unions when needed:
types.ts
type TypeA = {
name: string;
}
type TypeB ={
name: number;
}
export type {TypeA, TypeB}
You can then use these types like this:
import {TypeA, TypeB} from './types';
let myVar: TypeA | TypeB;
Or
import * as types from './types';
let myVar: types.TypeA | types.TypeB;
Scenario 2: Create union types directly in a module for ease of use:
types.ts
type TypeA = {
name: string;
}
type TypeB ={
id: string;
}
export type Types = TypeA | TypeB
To use them:
import {Types} from './types';
let myVar: Types;
If you need to utilize union types in GraphQL, check out the resources mentioned here.
Update: Regarding accessing all types within a module, it's not possible with interfaces
or types
as they are only compile-time entities for specifying object structures. Unlike classes
, you cannot extract all types at runtime using methods like Object.keys
or Object.entries
.
Your best approach would be to define union types in the types file or create the union type directly there and import/use them in your main file.