Implementing generics in TypeScript for objects made easy with this guide!

My question is regarding a function that utilizes generics and selects data from an object based on a key. Can we use generics inside the type of this object, or do we have to create a separate function for options?

enum Types {
  book = 'book',
}

type Base = {
    config: any
}

type Options<T> = {
    title: string,
    config:T
}

// How can we pass a generic "Desired" from getBooks into these options?
const options: Record<Types, Options<??>> = {
  book: [{title:'title', config: ['some data']}]
}

const getBook = <Desired extends Base>(type: Types) => {
      return options[type]
}


getBook(Types.book)

Answer №1

Sure, let's break down the definition based on the object provided.

{                      // object
  book: [              // Record<Type, Array< ? >>
    {                  // Record<Type, Array<object>
      title: 'title',  // Record<Type, Array<Options< ? >>
      config: [        // Record<Type, Array<Options<Array< ? >>>
        'some data'    // Record<Type, Array<Options<Array<string>>>
      ]  
    }
  ]
}

You could express this as

Record<Types, Options<string[]>[]>
, but I personally prefer writing it as
Record<Types, Array<Options<string[]>>>
with more spacing between the brackets.

Another interpretation could be that each array is a tuple with only one element, making the type

Record<Types, [ Options<[string]>> ]
. However, it's unclear if this was the desired structure.

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

Error: Unexpected input detected in `ts.resolveTypeReferenceDirective`. This issue may lead to a debug failure

I'm encountering the error below: { "name": "Angular", "version": "1.0.0", ... } If anyone has insights on what steps to take next or the potential cause of the problem, your input would be greatly a ...

Using ngIf to validate an empty string in Angular 5

I need assistance with validating an empty string retrieved from a server Although it is usually straightforward, it's just not working as expected <div class="ui-g-2 info-txt" *ngIf="appointment.Notes !==null || appointment.Notes !== ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...

What is the process of implementing a particular FormControl from a FormArray in my HTML file?

My FormArray initialization code is as follows: this.contents.forEach(content=> { this.formArray.push( new FormControl(content.text, Validators.required)); }); Now, I am trying to associate a specific FormControl with my textarea by using i ...

Deliver the commitment to the data source connection settings in TypeORM

Is it possible to retrieve the datasource connection options from AWS Parameter Store instead of storing them as environment variables in a general JavaScript question? I am having difficulty finding a solution and seeking expert advice on this matter. Th ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

What is the name of the file that contains a class?

I am curious about identifying the file that called a specific class: database.ts class Database { constructor() { console.log(`I want to know who called this class`); } } server.ts import Database from 'database.ts'; new Databa ...

The supabase signup function keeps showing me the message "Anonymous sign-ins are disabled." Can anyone help me understand why this is happening?

I'm currently in the process of setting up authentication in Next.js with supabase, but encountering an issue when attempting to execute the signUp function. The error message I'm seeing is: Anonymous sign-ins are disabled Below is the snippet o ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Error: Unable to set value, val.set is not a defined function for this operation (Javascript

Encountering a problem while running the function val.set(key, value), resulting in a type error TypeError: val.set is not a function within the file vendor-es2015.js. Here's the simplified code snippet: import { Storage } from '@ionic/storage& ...

Using TypeScript with GraphQL Fetch: A Guide

I came across a similar question that almost solved my issue, but it didn't quite work for me because the endpoint I'm using is a graphQL endpoint with an additional nested property called query. For instance, if my query looks like this: const q ...

Discover how to access and manipulate JSON files in an Angular application using

Currently, I am diving into learning TypeScript with Angular and I'm interested in reading a JSON file. The structure of my JSON file is as follows: { "nb": "7", "extport": "1176",, "REQ_EMAIL": ...

What is the most appropriate form to use, and what factors should be considered in determining

Incorporating generics in typescript allows me to create a generic function in the following manner: Choice 1 declare function foo1<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } Alternatively, I have the option to omit the seco ...

Getting pictures dynamically from the backend with unspecified file types

Greetings to my fellow Stackoverflow-Users, Lately, I was tasked with the requirement of loading images dynamically from the backend into my application. Up until now, it was always assumed that we would only be dealing with SVG images since there was no ...

Canceling a promise in a Vuex action

I am looking to implement the ability to cancel a running promise in my Vue component, specifically a promise returned by a Vuex action. In my scenario, the Vuex action is continuously polling an endpoint for status updates, and I need the capability to s ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...