Typescript tip: Identify whether a specified interface is within a type alias

I have created a type alias that is used on multiple interfaces:


export interface A {}
export interface B {}
export interface C {}
export type Reference = A | B | C;

In my code, I have a method called getReference which by default returns an array of the Reference type. However, I want this method to be able to take a generic type as input and check if the given type is part of my type alias.

Current implementation:


export const getReference = (slug: ReferencesSlugs): (state: object) => Array<Reference> => {
   ....... // some code
   // return Reference[]
}

Desired implementation:

We want developers to pass a generic type parameter to the method, and TypeScript should verify if the specified type is included in the Reference type alias.


export const getReference = <T>(slug: ReferencesSlugs): (state: object) => Array<T> => {
    ....... // some code
    // If T is within the Reference type -> return an array of T
}

this.store.pipe( select(getReference<A>('onchonch')) ); // This is valid, tslint approves
this.store.pipe( select(getReference<E>('onchonch')) ); // This is invalid, E is not part of the defined type alias.

Thank you in advance :)

Answer №1

If your union members (referring to the union in the type alias) are more complex than those mentioned in your initial question, you have the option to apply a type constraint on your generic type parameter:

export interface A { a: number; }
export interface B { b: number; }
export interface C { c: number; }
export interface E { e: number; }
export type Reference = A | B | C;

export const getReference = <T extends Reference>(slug: ReferencesSlugs): (state: object) => Array<T> => {
    return null!;
}

getReference<A>('onchonch'); // This is valid and tslint approves
getReference<E>('onchonch'); // This is invalid because E is not included in my type alias.

The significance of the member structures lies in typescript's use of structural compatibility in determining type compatibility. This means that if two types share the same fields, they will be considered compatible. It also implies that two empty interfaces will be compatible as well.

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

After encountering an error, the puppeteer promptly shuts down the page

During my page testing, an error is thrown by a dependency. Although the error is not critical and does not impact my application, when testing with Puppeteer and encountering this error, it abruptly closes the tested page. How can I bypass this error to c ...

Fulfill several promises and execute an HTTP request in Angular 2

At this moment, I am in need of retrieving two elements from my storage, each providing me with a promise. The challenge lies in using these promises to create an HTTP request in Angular 2. Despite numerous attempts, I have been unsuccessful in finding the ...

Dealing with Typing Errors in Angular with Typescript: Error message 'x' is not a function

I'm facing an issue in my schedule.component.html where I am trying to create a button and link its click event with a function defined in the associated schedule.component.ts file. The button is coded like this: <button type="submit" ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

Testing node.js/typescript: The unit test is expected to return a 201 response code

I encountered an issue with a test labeled 'should return 201 response code' that is failing: Expected: 201 Received: 200 orderController.ts import { Request, Response } from "express"; import { Orders } from "../models/orders&quo ...

What is the best way to save the output of the services function as an array of objects in a separate TypeScript file?

I need to store the result of a function in my services into an array of objects in my TypeScript file. getserver(id:number) { const server = this.servers.find( (s) => { return s.id === id; } ) } The return type of this fu ...

Oops! An unexpected error occurred while parsing the JSON response

While working with my Json file, I encountered an error that has been validated on https://jsonlint.com/ @Injectable() export class LightParserService{ ITEMS_URL = "./lights.json"; constructor(private http: Http) { } getItems(): Promise<Light[ ...

Developing Components in Angular 2.0 with the assistance of ui-router

I am currently in the process of transitioning an Angular 1.x application to utilize Angular 1.5 components, a new feature that will be relevant for Angular 2.0. As far as I can tell, I need to create a Root Component that will serve as the main bootstrap ...

What is the technique for retrieving variable types from beyond the function's scope?

I am facing a challenge with a function where I have declared a variable with a somewhat complex structure: export function foo() { const myVar = { // some properties with complex types here... } // Do something with `myVar` } Now, I ...

Is TypeScript the new replacement for Angular?

After completing a comprehensive tutorial on Angular 1.x, I decided to explore Angular 2 on angular.io. However, upon browsing the site, I noticed references to Typescript, Javascript, and Dart. This left me wondering if my knowledge of Angular 1.x is now ...

Configuring TypeScript types for nameless functions sent to Ramda

Having trouble determining the correct typings for the Ramda cookbook method mapKeys as it is not transpiling and throwing an error. Challenge The issue lies with fn: Error message: Argument of type '{}' is not assignable to parameter of typ ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

The properties required for type 'never[]' are not present

The type 'never[]' does not have the necessary properties from type '{ login: string; id: number; node_id: string; avatar_url: string; url: string; }': login, id, node_id, avatar_url, url When working on a component that takes an ApiUr ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

Is there a way to toggle or collapse a table row with a unique identifier using Angular and Bootstrap?

Currently handling Angular and Bootstrap in my work, but facing challenges with table manipulation and collapsing rows. I fetch data from a database and showcase it in a dynamically generated table using *ngFor and two rows within an ng-container. My goal ...

Managing API call limits using RxJs

Currently, I am in the process of developing an Angular application that utilizes an API provided by a social network. Unfortunately, this API has a restriction of only allowing 5 API calls per second. The typical solution to this limitation involves impl ...

How can NodeJS retrieve objects with dynamic child properties from MongoDB?

I need to retrieve an array of documents where a child property is set to true. Below is the code snippet I am using: public static getTeams(req, res) { // Establish connection to the database Globals.initDb(res).then((db: Db) => { // A ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

Please refrain from proceeding until the data recovery process is complete

I am currently facing a priority issue in my code. The problem arises when I call a web service and attempt to retrieve usernames based on user IDs from an array (listePasseoDemandesEnCours) using a foreach loop. this.ws_demandes_en_cours.getDemandesEnCour ...

Ways to transfer information from the parent component while the component is repeatedly utilized on the page

Consider the following situation within Angular 6: There is one upload component that is being utilized twice on the same page. By clicking the add button on any upload component using a behavior subject, data specific to that upload component can be obt ...