Retrieve the value of a property within the same interface

Is there a way to access an interface prop value within the same interface declaration in order to dynamically set types?

I am attempting something like this:

export type MethodNames = "IsFallmanagerUpdateAllowed" | "UpdateStammFallmanager";

export interface IsFallmanagerUpdateAllowed {
  plcParameter : StammFallmanagerParameter
}

export interface UpdateStammFallmanager {
  plcParameter : StammFallmanagerParameter
}

export interface ServerTaskParam<T> extends system.ServerTaskParam<T> {
  name       : `${Class.NAME}`,
  methodName : MethodNames,
  paramObj   : // here depending on the passed methodname type should be IsFallmanagerUpdateAllowed or UpdateStammFallmanager
  // paramObj   : T -> this is what I use atm but I want to make it more dynamic
}

Note that there could be more MethodNames.

The goal is for intellisense to indicate directly which type of object should be used as paramObj when passing name and methodName.

If possible, it should be something like this:

export interface ServerTaskParam extends system.ServerTaskParam {
  name       : `${Class.NAME}`,
  methodName : MethodNames,
  paramObj   : [ methodName ] -> use methodName value to refer to one or the other interface in the same namespace (pseudo syntax)
}

I have been searching online for solutions but haven't found anything. Is this concept feasible?

Answer №1

I believe a union is what you're looking for:

export type ServerTaskParam = ({
  name       : `${ClassName}`,
  methodName : "IsFallmanagerUpdateAllowed",
  paramObj   : IsFallmanagerUpdateAllowed
} | {
  name       : `${ClassName}`,
  methodName : "UpdateStammFallmanager",
  paramObj   : UpdateStammFallmanager
}) & system.ServerTaskParam

Playground

Answer №2

To streamline your code, consider creating a composite type that encompasses all possible interfaces. This "higher type" allows you to utilize its keys in the following manner:

export interface IsUpdatePermitted {
  parameter : ManagerParameters
}

export interface UpdateManager {
  parameter : ManagerParameters
}

interface Actions {
  IsUpdatePermitted: IsUpdatePermitted;
  UpdateManager: UpdateManager;
}

export interface TaskParameter<K extends keyof Actions> extends system.TaskParameter<T> {
  name       : `${ClassName}`,
  methodName : K,
  paramObject   : Actions[K]
};

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

Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong? import { Injectable } f ...

Storing information retrieved from the API for use in different modules

Trying to extract data from a WEB API service using Angular 8 has been quite challenging for me. A service I created makes the API call: return this.http.get<UserSession>(uri) .pipe(map((json: UserSession) => this.EntryFormAdapter(json))); Th ...

Tips for invoking both a typescript arrow function and a regular javascript function within one event

Is it possible to call both a JavaScript function and a TypeScript function from the same onClick event in a chart? I am new to TypeScript and Angular, so I'm not sure if this is achievable. The issue at hand is that I need to invoke a JavaScript fun ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

Creating a versatile function that can function with or without promises is a valuable skill to have

I am currently working on developing a versatile sort function that can function with or without promises seamlessly. The intended structure of the function should look something like this: function sort<T>(list: T[], fn: (item: T) => string | nu ...

Issue when retrieving child elements in Next.js server-side component

"use client"; -- Imports and interfaces const SubscriptionDataFetcher: React.FC<SubscriptionDataFetcherProps> = ({ children }) => { const [data, setData] = useState<SubscriptionData>({}); -- Functions return <> ...

How to Toggle Visibility of Angular2 Material Drop Down Menu?

My Code <mat-form-field class="button-spacing"> <mat-select placeholder="select" [(ngModel)]="dropDownOne"> <mat-option *ngFor="let first of test1" [value]="first"> {{ first }} </mat-option> </mat-select> </mat-fo ...

TypeScript's robustly-typed rest parameters

Is there a way to properly define dynamic strongly typed rest parameters using TypeScript 3.2? Let's consider the following scenario: function execute<T, Params extends ICommandParametersMapping, Command extends keyof Params, Args extends Params[C ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

Is there a way to ensure a consistent return value when using exhaustive switch-case statements?

I'm facing an issue with the following code snippet: function (flavors: IceCreamFlavor): 'like'|'dislike' { switch (flavors) { case IceCreamFlavor.vanilla: return 'dislike'; case IceCreamFl ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

Can an interface be designed to have the option of containing either one property or another?

I am in need of an interface that resembles the following structure: interface EitherOr { first: string; second: number; } However, I want to make sure that this interface can only have either the property first or second. Do you think achieving this ...

The parameter type (key: string, id: string, pagination: number) in the argument does not match the expected type of Boolean for the parameter

I'm facing an issue while trying to implement the following documentation: https://swr.vercel.app/ using my own setup: import React, { useEffect } from 'react' import PatientsTable from 'components/patients/PatientsTable' import ...

Issues with Tagged Union Types in Visual Studio Code

Currently, I am working on implementing a tagged union type pattern for my action creators within a redux application. The TypeScript compiles without any issues, however, my code editor, Visual Studio Code 1.26.1, is flagging an error. [ts] Type &ap ...

Issue with retrieving properties in Angular template due to undefined values in HTML

As a newbie to Angular, I am dedicated to improving my skills in the framework. In my project, I am utilizing three essential files: a service (Studentservice.ts) that emits an observable through the ShowBeerDetails method, and then I subscribe to this ob ...

Issue encountered while attempting to utilize a basic redux reducer to define a boolean value, regarding a mismatch in overrides

Currently, I am working on a project to enhance my understanding of Redux and Typescript. I am still navigating through the learning curve in this area. Based on what I have learned from a book, I have established a "slice" that includes definitions for r ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

Switching "this" keyword from jQuery to TypeScript

A piece of code is functioning properly for me. Now, I aim to incorporate this code into a TypeScript application. While I prefer to continue using jQuery, I am unsure how to adjust the use of this to meet TypeScript requirements. if ($(this).width() < ...