Ways to retrieve data types from the values of a different interface

Imagine having an interface called TableHeader:

interface TableHeader{
  key: string,
  value: string,
}

Next, we need to create an interface for TableData, where:

interface TableData{
  // ????
}

In this table data, the key should be of the type that matches one of the keys in TableHeader[],

for instance if we define

const tableHeaders : tableHeader[]=[
 { key: 'index', value: 'Index'},
 { key: 'firstName', value: 'First Name'},
 { key: 'lastName', value: 'Last Name'}
]

then, when we declare

const tableData: TableData[] = [
  {
   // each object in this array must include keys `index`, `firstName`, `lastName` 
   // along with their respective values (e.g. strings).
  },
  {
    .
    .
    .
  },
]

What would be the best way to accomplish this?

Answer №1

Here is the provided code:

// Table.ts

export interface Header<K>
{
    key: K;
    value: string;
}

export interface Data<K>
{
    key: K;
    value: string;
}

export class Table<K>
{

    headers: Header<K>[];
    data: Data<K>[];
    keys: K[];

    constructor()
    {
        this.headers = [];
        this.data = [];
        this.keys = [];
    }

    addHeader(...newHeader: Header<K>[]): void
    {
        this.headers.push(...newHeader);
        for (let i = 0; i < newHeader.length; i++)
            this.keys.push(newHeader[i].key);
    }

    addData(newData: Data<K>): void
    {
        if (this.keys.includes(newData.key))
        {
            this.data.push(newData);
        }
        else
        {
            throw "Data key does not exist in input array";
        }
    }

}

// Usecase.ts

import { Table } from './Table.js';

type Keys = "index" | "firstName" | "lastName";
let table = new Table<Keys>();

table.addHeader(
    {
        key: "index",
        value: "ID"
    }
);

try
{
    table.addData({
        key: "index",
        value: "456789"
    });
} catch(error) {
    console.log(`Error occurred: ${error}\n`);
}

console.log(table);

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

Having trouble getting undefined values for keys while attempting to retrieve all the data from Firebase DB with Angular

Currently, I have code that is fetching records from the Firebase database using both Angular and Ionic. The code functions properly, but it does not provide me with the keys for each record. Instead, it returns 'undefined'. I have researched s ...

The Function-supported Operation is having trouble implementing a modification related to Geohash/Geopoint - the Object Type requires a String format

Summary: My function-based Action that tries to set a GeoPoint as a Geohash property is failing with an error suggesting it was anticipating a string. I have an Object Type with a String property that has been designated as a Geohash in the property edito ...

Redux-toolkit payload does not recognize the specified type

While working on my project, I encountered an issue when using redux-toolkit. I have created the following reducer: setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => { let gridPolygonsData: GridPolygonsData; const { ...

NestJs Function yielding inconsistent results based on its calling location

There is a puzzling issue that I am unable to solve. I have stored priceHistories in memory within an array. Strangely, when I invoke a get method, the returned value varies depending on where the method is called from. This is the original property and m ...

Implementing multi-select checkbox feature in Angular 7 using ng-select

I'm looking to create a function where selecting an item will make the corresponding div appear. For instance, if I choose Crédit bancaire and Compte courant associé, the two corresponding divs should be shown. Check out this example: https://stac ...

Typescript's Intersection Types: The Key to Overlapping Properties

Looking to create a type-safe utility function in Typescript 4.0 for comparing properties of two objects, my initial code snippet is below: export function propertiesMatch<O extends object, T extends O, S extends O>(first: T, second: S, props: (keyof ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: https://i.sst ...

Is it feasible to mock a defined function in Typescript for a unit test scenario?

Currently, I am working on typescript code that compiles into javascript, gets bundled with rollup, and is utilized by a framework. This framework exposes a library to me in the global scope, taking the form of a function: fun({ prop1: number, ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

Using Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...

Retrieve a specific subdirectory from the bundle

I've developed a Typescript package with the following file structure: package.json src/ index.ts common/ index.ts sub/ index.ts My goal is to import certain modules from the package like this: import {...} from '<package>&ap ...

Unable to break down the property 'desks' of '(0 , _react.useContext)(...)' due to its undefined nature

Trying to mock DeskContext to include desks and checkIfUserPresent when calling useContext is causing an error to occur: Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined TypeError: Cannot destruct ...

Verify whether the default export of a file is a React function component or a standard function

Trying to figure out how to distinguish between modules exporting React function components and regular functions. Bun employs file-based routing, enabling me to match requests with module files to dynamically import based on the request pathname. Conside ...

Refine the primary list by narrowing it down according to a secondary list

I created a filterList function to compare a mainList with a subList1. The function's goal is to identify the elements in the main list that are not present in subList1 and store them in subList2. public filterList(mainlist: Selectitem[], subList1: S ...

Transferring an array of interfaces between Angular 2 components

Encountering issues with passing an Array of data between components using @Input. Here is the code snippet: public ngOnInit() { this.applications = new Array<ApplicationEntryInterface>(); (...) let shortTermData = new ShortTermApplicationAdapte ...

Solving the issue in Next JS: Troubleshooting the Error: connect ECONNREFUSED 127.0.0.1:3003 in TCPConnectWrap.afterConnect [as oncomplete]

I recently started using Next JS and I'm having trouble building my application locally. When I run the npm run build command, I encounter the following errors: ... _currentUrl: 'http://localhost:3003/data/menus.json', [Symbol(kCapture)] ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

When utilizing express-handlebars to render, the error message "req.next() is not a valid function

Trying to display the login page of a web application. Developed using TypeScript, node.js, express, and express-handlebars The code being executed is as follows: import exphbs = require("express-handlebars"); import cookieParser = require(&quo ...