Develop a set of matching key/value pairs using TypeScript

Looking to develop a custom data type where InputKeys will serve as the keys, and the values will be key/value pairs. The keys should correspond to InputFieldKey, with the value being a string.

My current progress includes {[key: string]: string}, but I need the key in this context to relate to the main key.

I've successfully established a parent-child relationship using <Record, for the parent part. However, I am struggling with constructing the child part which necessitates another layer of parent/child connections.

There could be varying numbers of ???InputFieldKeys, each containing multiple fields beyond just 3 like (firstName, lastName, ..., ...)

I am open to adjusting the code as needed to achieve the desired structure, and potentially utilizing generics if beneficial.

type InputKeys = 'user' | 'building'

type UserInputFieldKey = 'firstName' | 'lastName' | 'age'
type AddressInputFieldKey = 'line1' | 'line2' | 'zip'

type InputError = Record<InputKeys, {[key: string]: string}>

const errors: InputError = {
  user: {
    firstName: 'First name must be entered',
  },
  address: {},
}

Guidance on this matter would be greatly appreciated.

Answer №1

If you were to manually perform this task, it seems like the structure you're aiming for is as follows:

interface InputErrorManual {
    user: {
        firstName?: string;
        lastName?: string;
        age?: string;
    },
    address: {
        line1?: string;
        line2?: string;
        age?: string;
    }
}

You have the option to do it that way.


If you prefer the compiler to handle it programmatically, then you must specify the parent/child relationship in a mapping type, such as shown below:

type InputKeyMapping = {
    user: "firstName" | "lastName" | "age";
    address: "line1" | "line2" | "zip"
}

You can utilize a mapped type to transform this into the desired structure:

type InputError = {
    [K in keyof InputKeyMapping]: Partial<Record<InputKeyMapping[K], string>>
};

You can confirm that this matches the structure of InputErrorManual.


Now, let's put them to the test:

const goodErrors: InputError = {
    user: {
        firstName: 'First name must be entered',
    },
    address: {},
}; // should work fine

const badErrors: InputError = {
    user: {
        lastName: "bad name",
        line1: "oops" // error!
    },
    address: {
        line1: "bad line",
        age: "oops" // error!
    }
}

Whether using manual or programmatic mapping is more suitable for your scenario, both methods should serve your needs equally well.

Hopefully, this information proves helpful; best of luck!

Playground 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

The Angular 2 UI is unable to successfully connect with the controller through the API call

When attempting to call a URL from Angular 2 using http.get(), an exception is being thrown and the debugger in the controller is not being hit. Although I have checked the proxy and routing, they are the same as my existing projects. This new project is c ...

Implementing the handling of multiple button events in a ListView through onclick function

Currently, I have a listview with three buttons that need to trigger the same method checkInstall on multiple button clicks. However, I am unsure of how to achieve this. Below is the relevant code snippet: html file: <ListView [items]="allAppsList" c ...

Enabling CORS header 'Access-Control-Allow-Origin' in Angular 2 using Typescript

I am currently developing an Angular 2 typescript application on my localhost. I recently encountered an issue when trying to access an external REST API in my application, resulting in the following error message: Cross-Origin Request Blocked: The Same ...

The subsequent code still running even with the implementation of async/await

I'm currently facing an issue with a function that needs to resolve a promise before moving on to the next lines of code. Here is what I expect: START promise resolved line1 line2 line3 etc ... However, the problem I'm encountering is that all t ...

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...

Bringing in AuthError with TypeScript from Firebase

Is it possible to verify if an error is of type "AuthError" in TypeScript when using Firebase? I have a Https Callable function with a try/catch block that looks like this: try { await admin.auth().getUser(data.uid); // will throw error if user doesn& ...

Command to update a document in AWS DynamoDB using the Document Client

While attempting to utilize the UpdateCommand feature within the AWS DynamoDB documentation, I encountered various challenges due to its lack of detailed explanation and difficulty in implementation. My aim was to employ the update command to seamlessly t ...

When using tsdx with React, null values can prevent proper usage of hooks

Recently, I attempted to develop a React TypeScript component using tsdx for compilation and encountered a roadblock while debugging. The package appears to be successfully published and installed without any errors. However, when trying to use it, I consi ...

Error: Gulp is using ts-node and returning 'void' instead of 'Task', but it cannot find the type 'Task'

Seeking assistance from experienced individuals in the realm of gulp.js and typescript - could someone provide guidance for a struggling newcomer? I am currently utilizing the most recent versions of all relevant tools (node, ts-node, gulp, ts, @types/gul ...

Guide to Setting Up "Remember Me" Login for Users in Angular

I am having trouble setting the 'Remember Me' option on my Login page. I tried using localstorage session but it seems like something is missing in the service file that's causing it not to respond properly. I attempted to follow a guide on ...

Are optional parameters in TypeScript distinct from parameters that have the ability to be undefined?

Is there a distinction between the following two code snippets? function sayHello(name?: string) { if (name) { return 'Hello ' + name; } return 'Hello!'; } and function sayHello(name: string | undefined) { if (name) { return &apo ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

What is the reason for TypeScript not displaying a type mismatch error in this particular instance?

After starting to use React with TypeScript, I defined my types as follows: type CardInfo = { cardIndex: null | number; title: string; note: string; _id: string; from: string; cardId: string; }; type ContentType = { title: string; note: st ...

Learn How to Implement Styling in Material UI using Styled Components

Utilizing styled-components with MaterialUI integration. Encountering the following error in LoginTextField component and seeking a resolution. Error Message: [ts] Type '{ width: number; }' is missing the following properties from type &apos ...

The name 'BrowseAnimationModule' cannot be located

Can someone help me figure out how to install or fix this import issue I'm having with the 'animations' directory in @angular/platform-browser/animations not importing properly? import {CommonModule} from '@angular/common'; import ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

Unable to resolve every parameter

I am facing an issue while trying to inject a service into my component, resulting in the following error: https://i.stack.imgur.com/zA3QB.png news.component.ts import { Component,OnInit } from '@angular/core'; import { NewsService } from &apo ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...