Defining our own properties within a TypeScript reference interface

Is it possible to use the type of a property of an Interface as a generic in TypeScript? I have some code that demonstrates what I'm trying to achieve:

In the example below, I show how we can normally define types using enums and interfaces:

enum Sections {
  users = 'users',
  projects = 'projects'
}

interface SectionEles {
  [Section.users] : {...};
  [Section.projects]: {...};
}

interface SezViewSettings<S extends Sections> = {
  section: S;
  where: Array<keyof SectionEles[S]>;
}

While the above code works fine, I am curious if it's possible to avoid making SezViewSettings a generic. Instead, I would like to infer the type S from the value assigned to the property section, similar to this:

interface SezViewSettings = {
  section: S extends Sections;
  where: Array<keyof SectionEles[S]>;
}

Do you think this is achievable?

Answer №1

An interface is unable to capture this limitation without utilizing generics.

In scenarios like these, where your potential S types are enumerable, you can create a union of SezViewSettings<S> for all feasible S values and use it as the type. This approach may fulfill your requirements.

One method to achieve this is by constructing a mapped type where properties are promptly looked up:

type SezViewSettingUnion = { [S in Section]: SezViewSettings<S> }[Section]
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
     SezViewSettings<Section.projects>
*/

Likewise, you can employ distributive conditional types:

type _SezViewSettingUnion<S extends Section> =
    S extends any ? SezViewSettings<S> : never;
type SezViewSettingUnion = _SezViewSettingUnion<Section>;
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
SezViewSettings<Section.projects> */

Both approaches result in the same type output, which is equivalent to

SezViewSettings<Section.users> | SezViewSettings<Section.projects>
.


Hopefully, this explanation proves useful to you; best of luck!
Link to code

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

Showing a div based on the selection of multiple options from a multiselect

I am having trouble implementing a show/hide functionality based on a multiselect dropdown in my Angular and Typescript project. Specifically, I want to display a div with another dropdown menu when the user selects a certain option from the multiselect ...

Changing the Angular 5 ng-bootstrap Modal Dialog template dynamically in real-time

I'm currently developing a modal dialog that requires the ability to dynamically change the templateURL. The code shown is the default template, but I need to be able to swap it out dynamically. I'm unsure of how to achieve this, as the templateU ...

Issue with typing useMutation in ReactQuery

As I develop a basic app with authorization features, I am storing user data in a database. To send POST requests to the server during registration, I am utilizing the `useMutation` hook along with the `axios` library. However, I have encountered a challe ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

Form submission returns JSON data with an undefined value from the server

I've been following a tutorial here but ran into some issues due to using newer versions of Angular and Ionic. This is an excerpt from my code: createReview(review){ let headers = new HttpHeaders(); headers.append('Content-Type&apo ...

Pass the type of object property as an argument in the function

I've been having trouble trying to figure this out and haven't been able to find a solution in the TS docs or examples I came across. Essentially, I'm working with a configuration specifying operations on object properties and looking to en ...

Ensure that an Enum is limited to only numerical values (implement type checks for Enum)

I am looking to enforce a Generic type to be strictly a numerical enum. This means that the values of the Enum should only be numbers. Here is an example: export type TNumberEnum<Enum> = { [key in keyof Enum]: number }; enum sample { AA, BB ...

Exploring the relationship between classes and objects within Angular

Is it problematic to use traditional classes and objects in Angular code? For instance, when refactoring to separate specific logic from messy code, I often create a separate file like logic-handler.ts and define a class like so... export class LogicHandle ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

Redirect user to the "Confirm Logout" page in Keycloak after refreshing the page before logging out

While working on a project with keycloak, I've encountered an issue that I can't seem to figure out. After logging in and navigating to my project's page, everything operates smoothly. However, if I happen to refresh the page before logging ...

Can you explain the significance of the angle brackets "<>" in a Typescript function declaration?

When working with TypeScript code, I often come across code enclosed in angle brackets, similar to HTML. Despite knowing that they are not HTML elements, and understanding that the content within the angle brackets represents types, I frequently encounter ...

Optional parameter left unassigned is not automatically determined as undefined

Why is TypeScript not inferring the optional parameter in this function as undefined when it's omitted from the call? function fooFunc<T extends number | undefined>(param?: T){ let x: T extends undefined ? null : T x = param ?? null as any ...

Tips on presenting an image from within an MP3 file within an image tag

Hello, I attempted to display the image retrieved from an mp3 file in an image tag using HTML and ReactJS. Here is the code snippet that I utilized. async getImageFromUploadedFile(framesRetrieved){ const imageArrayBufferRetrieved = framesRetrie ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...

Breaking up React code within the React.createElement() function

I am encountering an issue with lazily loaded pages or components that need to be rendered after the main page loads. When using createElement(), I receive the following error: LazyExoticComponent | LazyExoticComponent is not assignable to parameter of ty ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Alert: Attempting to access an undefined value in an indexed type

I would like to find a way in Typescript to create a hashmap with indexable types that includes a warning when the value could potentially be undefined during a lookup. Is there a solution for this issue? interface HashMap { [index: number]: string; } ...

Sharing AppSettings between an Angular project and ASP.NET Core in a seamless manner

Currently, I have a project set up using the VS 2022 ASP.NET Core with Angular template. The project itself is working well, but I am facing a challenge in trying to integrate the Angular app with the .NET Core's appsettings.json file for configurati ...

Find the length of time in Typescript (measured in hours, minutes, and seconds)

Trying to calculate the duration between two dates in TypeScript (Angular): 2021-11-19 21:59:59 and 2021-11-19 22:00:18 let startDate: Date = new Date(start); let endDate: Date = new Date(end); if(end != null) { let duration = new Date(endDate.getT ...