Steps to creating a Partial Pick attribute

I'm facing an issue with a function I have

function someThing(someArg: Pick<HTMLElement, 'id' | 'style'>) {...}

The problem is that I only want to apply certain styles to someArg.style, not all the styles from CSSStyleDeclaration. If I include all styles, the input of the function will become too large.

What I'm looking for is something similar to using Pick with

Partial<CSSStyleDeclaration>
instead of using Pick with CSSStyleDeclaration

Can anyone help me with how to achieve this?

Answer №1

To handle the complexity of your specific type, it is recommended to define a separate interface to clarify the structure:

interface CustomType {
  id: HTMLElement['id'],
  style: Partial<HTMLElement['style']>
}

function customFunction(customArg: CustomType) { }

customFunction({id: "id", style: {
  zIndex: "1"
}})

The usage of lookup types emphasizes the relationship between the id and style properties with those of HTMLElement. Alternatively, you could utilize simpler types like string and

Partial<CSSStyleDeclaration>
.

If you require a more dynamic approach like Pick for partial subproperties, you can create a mapped type. However, the necessity for this depends on your specific requirements.

UPDATE

If programmatically generating the type is essential (even for a small number of properties), you can define a PickPartial type to select from Partial properties instead of the properties directly. This assumes non-recursion for subproperties to be Partial:

type PickPartial<T, K extends keyof T> = {[P in K]: Partial<T[P]>};
  
function customFunction(customArg: PickPartial<HTMLElement, 'id'|'style'>) { }
customFunction({id: "1", style: {
  zIndex: "1"
}})

It's important to note that although id is technically typed as Partial<string>, mapped types do not alter primitives, so Partial<string> is equivalent to string. This maintains consistency with the CustomType interface defined earlier.


Hopefully, this clarifies the process for you. Best of luck with your implementation!

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 type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app. Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty fo ...

Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes. managenews.component.ts import { Component, OnInit } from ...

What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. Th ...

Assign the private members of the class to the arguments of the constructor

class Bar { #one #two #three #four #five #six #seven #eight #nine #ten #eleven #twelve #thirteen #fourteen #fifteen #sixteen constructor( one, two, three, four, five, six, seven, eight, ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Error: A stream was expected, but you provided 'undefined'. Please provide either an Observable, Promise, Array, or Iterable instead

I'm encountering an error while trying to catch errors in my Ionic-based application with Angular. In the create() method, I am attempting to create a new User. If the username already exists, I receive a response from the backend, but my method thro ...

Can you explain the distinction between declaring type using the colon versus the as syntax?

Can you explain the variation between using the : syntax for declaring type let serverMessage: UServerMessage = message; and the as syntax? let serverMessage = message as UServerMessage; It appears that they yield identical outcomes in this particular ...

Ways to dynamically authenticate in AuthGuard and return a true value

I am working on an auth guard that has multiple conditions, and I am looking for a way to dynamically return a true value. Here is the relevant code snippet: auth.guard.ts canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise&l ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef: @ViewChildren('img', { read: ElementRef }) images: Q ...

Is it possible in Angular to directly bind the emitted output of a component to a property?

My primary application component communicates with its sub components using @Output decorated properties on the subcomponent. The output properties utilize an EventEmitter<>(). Typically, these properties emit a simple boolean or number. I want to di ...

"iOS users have reported that notifications from Firebase have mysteriously ceased to

Yesterday evening, I was experimenting with Push Notifications from Firebase on my iOS application and everything was functioning correctly. I successfully sent a notification from a Cloud Function to a specific FCM token. However, this morning, notificat ...

What is the reason for Object.keys not returning a keyof type in TypeScript?

Wondering why Object.keys(x) in TypeScript doesn't return the type Array<keyof typeof x>? It seems like a missed opportunity as Object.keys outputs that by default. Should I report this on their GitHub repo, or should I just submit a pull reques ...

The error message "The export named 'render' (which was imported as 'render') could not be found" appeared

Encountering an error when building a Vue project with TypeScript and Webpack, specifically the "export 'render' (imported as 'render') was not found" issue. Below is the full error code: export 'render' (imported as 'ren ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

What is the solution for the warning "Solid's reactivity is broken when destructuring component props"?

Just starting out with SolidJS and encountering an issue with my UI setup import { render } from "solid-js/web"; import { createSignal, Show } from "solid-js"; import { createStore } from 'solid-js/store'; function Form() { ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Transform the MUI Typescript Autocomplete component to output singular values of a specific property rather than a complete object

When utilizing MUI Autocomplete, the generic value specified in onChange / value is determined by the interface of the object set in the options property. For instance, consider an autocomplete with the following setup: <Autocomplete options={top ...