Restrict the properties of an object to match the properties of a different object

I am currently developing an Object patching utility function with the following code snippet

class Test{
  a:number;
  b:number;
}

var c:Test={a:0,b:1}

function patchable<T>(obj:T){
  return {
    patch:function<K>(prop:K){
      return patchable({...obj,...prop})},
    value:function():T{return obj}
		}
}

c=patchable(c).patch({notAllow:94}).value()

Is it feasible in typescript to restrict the patch function to only accept objects containing properties that are present in the Test interface, meaning K can exclusively have keys available in T

Answer №1

class Sample {
  x: number
  y: number
}

var z: Sample = {
  x: 0,
  y: 1
}

function adaptable<U>(customObj: U) {
  return {
    modify: function <V extends keyof U>(property: Pick<U, V>) {
      return adaptable({ ...customObj, ...property })
    },
    result: function(): U {
      return customObj
    }
  }
}

z = adaptable(z).modify({ disallow: 94 }).result() // fails
z = adaptable(z).modify({ x: 94 }).result() // compiles

Answer №2

Another approach is to use the Partial method:

class Example {
  x?: number
  y?: number
}

var z: Example = {
  x: 0,
  y: 1
}
function editable<E>(object: E) {
  return {
    edit: function (property: Partial<E>) {
      return editable({ ...object, ...property })
    },
    showValue: function(): E {
      return object
    }
  }
}

z = editable(z).edit({ notAllowed: 94 }).showValue() // fails
z = editable(z).edit({ x: 94 }).showValue() // works
console.log(z)

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

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

Create a reusable React component in Typescript that can handle and display different types of data within the same

I have a requirement to display four different charts with varying data types. For instance, interface dataA{ name: string, amount: number } interface dataB{ title: string, amount: number } interface dataC{ author: string, amount: ...

Tips for creating an onClick event for a React Component that is passed as a prop to another component

I am currently in the process of creating a custom trigger component that can be passed down to another component. My goal is to implement a click event on this trigger component from the receiving component. If you'd like to see a live example, chec ...

Angular: Implementing conditional HTTP requests within a loop

Currently, I am facing a challenge where I need to loop through an array of objects, check a specific property of each object, and if it meets certain criteria, make an HTTP request to fetch additional data for that object. The code snippet below represen ...

React TypeScript - Module not found

Organizational structure: src - components - About.tsx In an attempt to optimize performance, I am experimenting with lazy loading: const About = React.lazy(() => import('components/About')); However, Visual Studio Code is flagging &ap ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

Querying Cloud Firestore with User ID

I'm facing an issue with retrieving a subset of data based on the first letter of the name and including the UID of the document. No matter what I try, it just returns empty data. fetchDataByFirstLetter(firstLetter: string) { this.afs.collection(&a ...

Unable to retrieve shared schema from a different schema.graphql file within the context of schema stitching

In my project, I have a user schema defined in a file named userSchema.graphql; id: String! userName: String! email: String! password: String! } In addition to the user schema, I also have separate schema files for login and register functionalit ...

Best practices for correctly parsing a date in UTC format using the date-fns library

My log file contains timestamps in a non-ISO format: 2020-12-03 08:30:00 2020-12-03 08:40:00 ... The timestamps are in UTC, as per the log provider's documentation. I am attempting to parse them using date-fns: const toParse = "2020-12-03 08:40 ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

Mastering Angular 2 Reactive Forms: Efficiently Binding Entire Objects in a Single Stroke

Exploring reactive forms in Angular 2 has led me to ponder the possibility of binding all object properties simultaneously. Most tutorials show the following approach: this.form = this.fb.group({ name: ['', Validators.required], event: t ...

Troubles encountered while trying to make MediaRecorder function in Angular 9

Recently, I've been working on integrating Media Recorder into my Angular 9 application by following the instructions provided at this link. However, I have encountered some issues along the way. When I access the page with the Media Recorder compone ...

Is it necessary for me to develop an Angular library in order to release a basic TypeScript class that makes use of Angular components?

In one of my Angular projects, I have a Typescript class called APIResponse that I want to convert into an NPM package for use in other projects. This class is not specific to Angular like a Service or Component. After doing some research on creating non-A ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

Issue with updating BehaviorSubject not being reflected when called from my service component has been identified

In my HomeComponent, I am currently using *ngIf to switch between 3 components. The focus right now is on the relationship between two of them - the ProductListComponent and the ProductDetailComponent. Inside the ProductListComponent, there is a ProductLis ...

What are some ways to retrieve a summary of an Angular FormArray containing controls?

In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed: FormGroup { controls { products (FormArray) { 0 : {summary.value: 5}... 1 : {summary.value: 8}.. there can be N of these co ...