Creating dynamic types in TypeScript through existing types

Consider the following object:

class Product {
  constructor(
    public metadata: Metadata,
    public topic: Topic,
    public title = 'empty'
  ) {}
  ...
}

I am looking to define an interface:

interface State<T> {
}

This interface should ensure that a product: State<Product> shares the same structure as the Product class, but all leaf-level properties are boolean. This means that the product object should have a title property of type boolean.


I reviewed the readonly example on mapped types, but it seems that in this case I may need a composite approach:

interface State<T> {
  [p in keyof T]: typeof T[p] === 'object' ? State<T[p]> : boolean;
}

Do you have any suggestions on how to implement this effectively?

Answer №1

Almost there, just a minor syntax error. Instead of using an interface, try utilizing a type. Additionally, replace typeof T[p] === 'object' with T[p] extends object.

class Metadata {
  constructor(
    public key = 'empty',
    public value = 'empty'
  ) { }
}
class Topic {
  constructor(
    public name = 'empty'
  ) { }
}
class Product {
  constructor(
    public metadata: Metadata[],
    public topic: Topic,
    public title = 'empty'
  ) { }

}

type StateWithoutObjects<T> = {
  [P in keyof T]: T[P] extends object ? StateWithoutObjects<T[P]> : boolean
}
let obj: StateWithoutObjects<Product> = {
  title: true,
  topic: {
    name: true
  },
  metadata: [
    { key: true, value: false }
  ]
}

Interactive Code Playground

Answer №2

Consider utilizing type in place of an interface:

type Status<T> = { [P in keyof T]: boolean };

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

Route.get() is expecting a callback function, however it received an object of undefined instead

In my nodejs application using typescript, I am working on separating the routing by introducing interfaces and controllers to handle the logic. app.ts const countryRoutes = require('./routes/countryroute') app.use('/countries', count ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

Typescript: issue with type guard functionality not functioning properly

type VEvent = { type: "VEVENT"; summary: string; }; type VCalendar = { type: "VCALENDAR"; }; const data: Record<string, VEvent | VCalendar> = (...); array.map((id) => { return { id, title: dat ...

I am looking to transfer 'beforeEach' and 'afterEach' from the spec file to the global configuration file in WDIO [mocha, hook, wdio]

My E2E testing setup involves using the WebdriverIO library along with the mocha framework. During test execution, I want Mocha to automatically skip all subsequent checks in a test after encountering the first error, and proceed to the next test file. T ...

Ways to address the error in typescript: "Namespace 'fastify' not found"?

Recently, I made the decision to update all of the packages on my fastify-server template. Upon inspection, my package.json file appears as follows: { "name": "backend-template", "version": "1.0.0", &quo ...

The output of switchMap inner will generate an array similar to what forkJoin produces

I have a series of observables that need to run sequentially, with each result depending on the previous one. However, I also need all the intermediate results in an array at the end, similar to what is achieved with the use of forkJoin. Below is the curr ...

What is the functionality of input onChange in React when using state management?

Whenever I try to log the value of the input after each onChange event, there seems to be an odd one event delay. For example, if 'some text' is the default input value and I remove the letter 't' by pressing backspace/delete, it first ...

How come the props aren't being passed from the parent to the child component? (React / TypeScript)

Learning TypeScript for the first time and facing an issue with passing props from parent to child components. The error seems to be related to the type of props, but I'm not sure how to fix it since all types seem correct. Error message: "Property ...

Is it beneficial to utilize an interface for constructing a class model?

The Interface: export interface IAddEditGeneralDictionary { Code: string; StartDate?: Date | string; FinishDate?: Date | string; Name: string; } The Realization: export class AddEditGeneralDictionary implements IAddEditGe ...

An effective way to define the type of a string property in a React component using Typescript

One of the challenges I'm facing is related to a React component that acts as an abstraction for text fields. <TextField label="Enter your user name" dataSource={vm} propertyName="username" disabled={vm.isSaving} /> In this set ...

What exactly does "tsc" stand for when I compile TypeScript using the command "(tsc greeter.ts)"?

What does tsc stand for when compiling TypeScript code? (tsc greeter.ts) tsc I'm curious about the meaning of tsc in this context. ...

Discover how to access JSON data using a string key in Angular 2

Trying to loop through JSON data in angular2 can be straightforward when the data is structured like this: {fileName: "XYZ"} You can simply use let data of datas to iterate over it. But things get tricky when your JSON data keys are in string format, li ...

Troubleshooting common issues while setting up React Native with TypeScript

After carefully following the steps outlined in this guide on configuring a React Native project using TypeScript: https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native, I encountered a total of fifteen errors from the ...

What is the best way to assign JSON values to my class property?

I've been working on a weather application that showcases the current weather of 5 different cities. By clicking on each city, users can access a detailed view displaying the 5-day forecast for that particular location. Currently, I have defined a we ...

Error encountered when initializing a variable within the constructor of a TypeScript file in Angular 4

This is the content of my app.component.html file PL Auth Username: Password : Generate OTP Enter OTP : Login This is the code in my app.component.ts file import { Component, OnInit } from '@angular/core' ...

Error encountered in Jest while searching for entities using the class: TypeORM RepositoryNotFoundError

Recently, I encountered a puzzling issue that has been quite challenging to debug. After upgrading all the project dependencies, my tests (using Jest 25.5.4 or 26.x) started failing with the dreaded "RepositoryNotFoundError." The peculiar thing is that al ...

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...

Tips on optimizing data processing for quicker display with ngFor

I am currently facing an issue with loading a JSON file containing 3500 data. The data appears very slowly on the view, causing the application to work sluggishly. Below is a snippet of the JSON: export class Service { private items = new Arr ...

The absence of the @Injectable annotation is causing an issue when importing a JSON

I am currently in the process of integrating a JSON file into my service by using a @inject() tag within the constructor. Below is the code snippet I am working with. DependencyInjectionContainer.ts import { Container, decorate, injectable } from "invers ...

The error TS2300 arises from the duplicate identifier 'PropertyKey' found in the node_modules/@types/core-js/index.d.ts file

I am encountering errors in the file node_modules/@types/core-js/index.d.ts while using Visual Studio Code IDE: https://i.sstatic.net/fkAej.png After running npm start to serve the application, the following errors are displayed: (list of errors her ...