Is it possible for two distinct TypeScript interfaces to share identical keys while allowing for varying values?

Is it possible in TypeScript to ensure that objValidator has the same keys as the obj it validates, with different key values? Any suggestions on how I can achieve this requirement? Specifically, the obj and objValidator should share identical keys.

I want to be notified if my objValidator does not possess the exact same keys as the obj.

interface obj {
  alpha: number
  beta: string
}

interface objValidator {
  alpha: {
    message: string
    valid(ALPHA'S TYPE): boolean
  }
  beta: {
    message: string
    valid(BETA'S TYPE): boolean
  }
}

Answer №1

Here is an example that demonstrates the use of mapped types with TypeScript:

interface Employee {
  name: string;
  age: number;
}

type Validator<T> = {
    [P in keyof T]: {message: string, valid: boolean};
};

let employee: Employee = { name: "John Doe", age: 30 };
let validator: Validator<Employee> =
{
  name: {
    message: "Name is required",
    valid: true
  },
  age: {
    message: "Age must be a number",
    valid: true
  }
}

Answer №2

My expertise may be limited, but I have a suggestion for addressing a similar need:

interface MyBase<X=any, Y=any> {
  first: X,
  second: Y,
}
export interface Example1 extends MyBase<string, number> {}
export interface Example2 extends MyBase<
  { description: string, value: Example1['first'] },
  { description: string, value: Example1['second'] }
> {}

// Now, let's try this out...
const sample1: Example1 = { first: 'greetings', second: 456 };
const sample2: Example2 = { 
  first: { description:'note', value: 'yes' },
  second: { description:'note', value: 456 },
};

Please keep in mind that enabling the allow empty interfaces setting in the tsconfig might be necessary.

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

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

Tips for troubleshooting TypeScript integration tests within Pycharm

Currently, I have been utilizing PyCharm to code in typescript. To run tests in the integration directory, I execute npm run test:integration. However, I am now looking to debug the tests. The directory structure looks like this: my_project /src /tests ...

Mastering the art of utilizing Function's construct signatures within TypeScript

Currently delving into the TypeScript documentation, specifically exploring More on Functions. However, I find myself perplexed by the code snippet provided below. Can someone offer guidance on how to implement this in practical development scenarios? An ...

Testing Slack's Web API with Jest for mock purposes

Currently, I am working with two files. One file is where I set up a slack web API client to post a message and test it with a mocked value: main.ts: import { WebClient } from '@slack/web-api'; const slack = new WebClient(process.env.SLACK_API_K ...

Managing a click event with an element in React using TypeScript

Hey there, I'm pretty new to TypeScript and React. I have this event where I need to identify the element that triggered it so I can move another element close to it on the page. However, I'm facing some challenges trying to make it work in React ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

Adding TH into a TABLE in Angular 2 by verifying TD elements

I am seeking a way to automatically generate thead and th, using td in the template : <Datatable> <tr #lineSelected *ngFor="let subscription of results"> <td nameColumn="Nom">{{subscription.name}}</td> <td n ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Changing the name of an Angular2 import module

Deciding to improve readability, I opted to rename the @angular module to angular2 and gain a better understanding of how imports function. Prior to making this change, the systemjs.config.js appeared like so: (function(global) { var map = { ...

Tips for linking my TypeScript document to the server

Recently diving into the world of Angular 2 and seeking to grasp its intricacies. Currently utilizing Visual Studio Code. How can I have the server monitor changes in the TypeScript file? Do I need a compiler to convert it to JavaScript for this purpose? ...

How to Reload the Active Tab in Angular 5?

In my project, I have noticed that a listener in one of the tabs causes the entire tab to refresh, resulting in it displaying information from the first tab until I switch to another tab and then go back. 1) Is there a way to refresh only the current tab? ...

Is there a way to access the value of the --base-href parameter in my Angular project during the build process?

In my Angular project, I have set up multiple environments for different stages of development, testing, acceptance, and production. Each environment has a specific base URL, which I designate using the --base-href flag during the project build. However, I ...

In Vue3, when using the `script setup` with the `withDefaults` option for a nested object, its attributes are marked as required. How can this issue

I have defined a props object with certain attributes: interface Props { formList: BaseSearchFormListItemType[], inline?: boolean searchBtn?: { show?: boolean text?: string type?: string size?: string } } const props = withDefaults( ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

Facing a 'No provider for' error in my Angular 2.0.0 application

I recently developed a service called SecurityService to handle authentication. Check out the code for this service below: import { Injectable } from '@angular/core'; @Injectable() export class SecurityService { items: any[]; construct ...

Dealing with mouseover and mouseout events for ul li elements in Angular 9: An easy guide

Having trouble showing and hiding the span tag using mouseover and mouseout events. The ul and li elements are generating dynamically, so I attempted to toggle the display between block and none but it is not working as expected. Does anyone have a solutio ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

Is there a way to customize the scrollbar color based on the user's preference?

Instead of hardcoding the scrollbar color to red, I want to change it based on a color variable provided by the user. I believe there are two possible solutions to this issue: Is it possible to assign a variable to line 15 instead of a specific color lik ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...