Typescript - any of the types imported from a module

Currently, my code looks like this:

import * as Types from '../schema/types';

and I'm looking to achieve something along the lines of:

let a: Types;

This would signify that a should be one of the various types exported from the file types.ts. Is there a way to accomplish this? (By the way, it's for a graphql server)

Answer №1

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.

Answer №2

Automating this process may prove challenging, but the key solution lies in utilizing a union type.

If you have previously defined types in the file ../schema/types, such as:

interface Foo {
 ...
}

interface Bar {
 ...
}

You can import them using

import * as Types from '../schema/types';

Subsequently, you can create a union type like so:

type GqType = Types.Bar | Types.Foo;

Finally, by declaring a with this new type:

let a: GqType;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

assign data points to Chart.js

I have written a piece of code that counts the occurrences of each date in an array: let month = []; let current; let count = 0; chartDates = chartDates.sort() for (var i = 0; i < chartDates.length; i++) { month.push(chartDates[i].split('-&ap ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Stop non-logged-in users from accessing page content rendering

Lazy loading is being used in my application to render pages. { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] } The problem arises when the user types www.mydomain.com/dashbo ...

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...

Tips for efficiently combining mergeMap observables and providing a singular value for the entire observable

Consider this particular case involving TypeScript/angular with rxjs 6.5: main(){ const items = ['session', 'user']; const source: Observable<any> = from(items); source .pipe( ...

Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows: const formService = new FormService(); const [appointmentDate, setAppointmentDate] = us ...

Oops! Looks like there was an error trying to assign the value "$event" to the template variable "element". Remember, template variables can only be read

Can anyone assist me in identifying the issue with this code? <div *ngFor="let element of list; let index=index"> <mat-form-field> <input matInput type="string" [(ngModel)]="element" name="element ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

The @Input directive is failing to receive any data from its parent component

Recently, I delved into the workings of Angular's @Input feature and have found it quite useful thus far. My database is Firebase, and the data snippet I am fetching looks like this: { "page_area_business_image" : { "expand" : { ...

Different States for a single element within the React + Redux Template in Visual Studio

I have come across an issue while using the Visual Studio 2017 React + Redux template. I followed the setup for stores as per their guidelines and everything was working fine so far. However, now I need to provide a component access to multiple states. The ...

Discussing recursive types A <--> B with generics in TypeScript

I'm currently working with the following TypeScript code: type DormNodePredicate = DormEdge | (() => DormNode<DormNodePredicateRecord>); interface DormNodePredicateRecord { [key: string]: DormNodePredicate; } export class DormNode<DNPR ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

What is the best method for saving the graphql response from "apollo-fetch" into a variable?

In order to enhance the efficiency of my code, I set out to extract the title, forename, and surname from a GraphQL response for an automated test. The initial implementation involved making separate HTTP requests for each value as shown below: const { cr ...

Cannot assign an array of Typescript type Never[] to an array of objects

Creating an object array can sometimes lead to errors, let's take a look at an example: objectExample[a].push({ id: john, detail: true }); objectExample[a].push({ id: james, detail: false}); const objectExample = { a = [ { id: john, detail: true} ...

Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsula ...

TypeScript implementation of a reusable component for useFieldArray in React Hook Form

I'm currently working on a dynamic form component using react-hook-form's useFieldArray hook and facing issues with setting the correct type for field. In order to configure the form, I have defined a type and default values: export type NamesAr ...

Combining Layouts and Providers: A Guide to Using Both on a Single Page

I am facing an issue with my provider that is responsible for refreshing a token by making a request to the server. Additionally, I have a basic layout featuring a sidebar that I want to use only on a specific route. However, I am unsure about where to add ...

There is no mistake when using a value that falls outside of a TypeScript

Expecting to encounter a compile time error with this code, but it seems my understanding of enums is off... enum SortDirection { ascending = 1, descending = -1 } type IndexSpec = {[index: string]: SortDirection}; var i: IndexSpec = {thing: 3}; ...

Tips for incorporating a fresh attribute into a class through a class decorator

Looking to add a new property to a class using a class decorator? Here's an example: @MyClassDecorator class MyClass { myFirstName: string; myLastName: string; } // Need to achieve something like this: function MyClassDecorator (target: any ...

In TypeScript, both 'module' and 'define' are nowhere to be found

When I transpile my TypeScript using "-m umd" for a project that includes server, client, and shared code, I encounter an issue where the client-side code does not work in the browser. Strangely, no errors are displayed in the browser console, and breakpoi ...