Modify the interface type whilst maintaining the structure of nested objects

In my system, I have a specific interface that outlines the structure of a NoSQL document schema. This includes strings, arrays, nested objects, and more. Here's an example representation:

interface IStudentSchema {
  name: string;
  age: string;
  foo: {
    a: number;
    b: [number, number];
    c: string;
  }
}

I am looking to create another interface that mirrors this same structure, but replaces each value type with a designated interface (excluding object types). Here's how I envision it should look like below. It should still preserve the original type and use it as a generic.

interface IStudentSchemaFieldInfo {
  name: ISchemaField<string>;
  age: ISchemaField<string>;
  foo: {
    a: ISchemaField<number>;
    b: ISchemaField<[number, number]>;
    c: ISchemaField<string>;
  }
}

I'm seeking a way to receive a compile-time warning if there are any modifications made to the original schema interface. Thus far, I've had to ensure they match manually.

While I can achieve this for non-nested objects using

Record<keyof IStudentSchema, ISchemaField>
, I still struggle with specifying generics for the ISchemaField interface. Any suggestions on how to tackle this?

Answer №1

To clarify the question, one way to achieve this is by expanding the child interface. Just a heads up, I switched the definition around - now the Schema holds the ISchemaField definition.

interface MysqlObject<T> {
  method<T>(): boolean;
}

type ISchemaField<T> = T | MysqlObject<T>;

interface IStudentSchema {
  name: ISchemaField<string>;
  age: ISchemaField<string>;
  foo: {
    a: ISchemaField<number>;
    b: ISchemaField<[number, number]>;
    c: ISchemaField<string>;
  }
}

interface IStudent extends IStudentSchema {
  name: string;
  age: string;
  foo: {
    a: number;
    b: [number, number];
    c: string;
  }
}

This approach maintains the structure of the original interface and will trigger a compile-time error if modified.

https://i.stack.imgur.com/xNwlE.png

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

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order t ...

Tips for effectively jasmine testing with the createSpyObj function, where class properties are defined as spies

When attempting to create a mock service with set-only properties, I encountered errors indicating that the value was undefined despite following the guidance in the documentation here. I want to be able to track the values of these properties during test ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

The type 'unknown' cannot be assigned to type 'KeyboardEvent'. Error in file 'ts' (2345)

Currently delving into TypeScript and Angular, I encountered an issue in my textbook with an example that refuses to compile. I am unsure of how to resolve this problem. Below is the malfunctioning function: ngOnInit(): void { const logger = fromEvent ...

Confirm the existence of a non-null value

One of the functions I have implemented is designed to remove null values from an array that is passed as input. This function also provides an optional transform functionality, allowing the user to modify the elements of the array into a custom format if ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

The Angular 4 HTTP patch method is encountering difficulties when called in code but functions properly when tested using Post

My attempts to make a patch and post call to the server are failing as it never reaches the server. Interestingly, the same request works flawlessly in Postman, so I suspect there might be an issue with my code. Both my post and patch methods are essentia ...

Guide to setting up Cosmos DB database connection using NestJS version 9.0.0

I'm encountering issues when attempting to include the Cosmos DB connection module in nestjs v9, as I'm facing dependency errors. Nest is unable to resolve the dependencies of the AzureCosmosDbCoreModule (COSMOS_DB_CONNECTION_NAME, ?). Please ens ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Global Declaration of Third-Party Modules for Seamless Use without Imports in Webpack5 with TypeScript

Within my React project utilizing Webpack, I have opted to declare certain modules as global entities to eliminate the need for importing them every time they are needed. In my Webpack configuration file: plugins: [ new webpack.ProvidePlugin({ ...

What could be causing the need for RxJs TypeScript files to be requested exclusively when my website is hosted on IIS?

When I develop my site using Visual Studio / IIS Express, everything runs smoothly without any unusual requests or 404 errors. However, once I publish the site to IIS and try to run it, I start receiving multiple requests for typescript files (.ts), prima ...

Creating a unified environment variable for Angular 2 and ASP.NET Core MVC: A comprehensive guide

In my ASP.NET Core MVC project, I am utilizing an Angular 2 application. Both the Angular 2 app and the Startup.cs file contain code that is specific to different environments. For example, using http://localhost as the web service URL during development ...

The field list contains an unidentified column named 'Test.computerIDComputerID'

I am currently navigating through the syntax of typeORM and have been stuck troubleshooting an issue for quite some time. It appears that whenever I utilize the find() function in typeORM, a query is generated with a duplicated column from a relation. Here ...

Passing data from child components to parent components in NextJs using Typescript

I have created a new component <ConnectWallet setConnected={(t: boolean) => console.log(t)}> <>test</> </ConnectWallet> The component is initialized as follows import { useState, useEffect } from ' ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

The state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...

Angular2 displays an error stating that the function start.endsWith is not recognized as a valid function

After switching my base URL from / to window.document.location, I encountered the following error message: TypeError: start.endsWith is not a function Has anyone else experienced this issue with [email protected]? ...

Access the global window variable from index.html within a Vue component

In my Vue project, I am incorporating an Stencil.js component in the following manner: index.html: <script type="module" src="https://xxxxxx.s3-eu-west-1.amazonaws.com/topbar.esm.js"> </script> <script> window.addEventLis ...

What methods are available to rapidly test Firebase functions?

While working with Typescript on firebase functions, I have encountered challenges in testing and experimenting with the code. Despite using the Lint plugin to identify errors without running the code, I am struggling to run the code and view the output. ...