Extending Interfaces Using Keys from an Array in Typescript

When dealing with a scenario where you want a pointfree omit, you can achieve this:

type PlainObject<T> = {[key: string]: T}

const omit = <K extends string>(
  name: K
) => <T, U extends PlainObject<T> & {
  [P in K]: T
}>(
  x: U,
): Partial<U> => {
  throw new Error ('Yet to implement !')
}

Is there a way to use K as an array of strings instead of just a string? Perhaps something like this:

const omit = <K extends string[]>(
  ...names: K
) => <T, U extends PlainObject<T> & {
  [P in K]: T // Type 'K' is not assignable to type 'string | number | symbol'
}>(
  x: U,
): Partial<U> => {
  throw new Error ('Yet to implement !')
}

The purpose here is to make the compiler flag any incorrect objects entered based on the keys passed:

omit('a', 'b')({b: 3, c: 4}) // => expect error

Thank you in advance
Seb

Answer №1

Absolutely, you can achieve this:

type ExcludeKey<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

declare function excludeKeys<K extends string>(...keys: K[]):
  <T extends Record<K, any>>(source: T) => ExcludeKey<T, K>;

Example of how to use it:

interface Person {
  name: string;
  age: number;
  job: symbol;
}

declare const person: Person;

excludeKeys('age', 'name')(person); // $ExpectType { job: symbol }
excludeKeys('foo', 'bar')(person);  // $ExpectError

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

Performing calculations on two properties of an observable object in Angular 8 and then storing the result in a new property

Looking for guidance on how to display the sum of two properties from an observable data. Take a look at the code below and let me know your thoughts: Typescript class export class Amount { Amount1: number; Amount2: number; Total:number; } In typescript ...

How to modify the background color within the mat-menu-panel

Incorporating angular 9 and less into my current project, I have encountered an issue with a mat-menu-panel where my mat-menu-item is located. While I have successfully changed the color of my mat-menu-item, I am now faced with the challenge of changing th ...

Implementing the 'colSpan' attribute in ReactJS

I encountered an error saying "Type string is not assignable to type number" when attempting to include the colSpan="2" attribute in the ReactJS TypeScript code provided below. Any suggestions on how to resolve this issue? class ProductCategoryRow exten ...

"Utilize the handle property of a component when interacting with the window.onclick

In my component, I have a property called enableButtons which is set to true when I click on an ion-menu label. However, I want this property to revert to false if I click anywhere else. Here's the code I tried: export class ProfilePage implements OnI ...

Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

Troubleshooting notifications generated by react-hook-form and zod

My customer registration form is causing all my error messages to show as "required." I suspect it might be a misconfiguration in zod or react-hook-form. Below, you'll find the code snippets. This is my generic input component: import { DetailedHTMLP ...

Encountering an error while trying to install DefinitelyTyped Typescript definitions via npm. Error message reads "Permission denied (publickey)."

I am currently facing an issue while attempting to set up the type definition for bleno from the DefinitelyTyped repository. The command I have been using is: npm install --save @types/bleno However, it appears that there are restrictions preventing me f ...

Passing a boolean value from the parent Stepper component to a child step in Angular

I am facing an issue with passing the boolean value isNewProposal from a parent Angular Material stepper component to its children steps. Despite using @Input(), the boolean remains undefined in the child component, even after being assigned a value (true ...

Angular 14 encountered an unexpected issue: There was an unhandled exception with the script file node_modules/tinymce/themes/modern/theme.min.js missing

After attempting to run ng serve, an error message appears: ⠋ Generating browser application bundles (phase: setup) ...An unhandled exception occurred: Script file node_modules/tinymce/themes/modern/theme.min.js does not exist. ⠋ Generating browser ap ...

Error message in Angular 2 RC-4: "Type 'FormGroup' is not compatible with type 'typeof FormGroup'"

I'm currently facing an issue with Angular 2 forms. I have successfully implemented a few forms in my project, but when trying to add this one, I encounter an error from my Angular CLI: Type 'FormGroup' is not assignable to type 'typeo ...

Guide on navigating to a different page using a function with router link in Angular using TypeScript

Trying my hand at Angualar and Typescript for the first time. I am working on creating a login page where users can move to another page if their credentials are correct. To achieve this, I want to use a function that is triggered by clicking a button. How ...

Unable to assign user roles in next-auth due to the absence of matching modifiers for user

I am currently working on implementing user roles in next-auth. Within my database, I have defined a prisma enum UserRole with the values 'ADMIN' and 'USER'. In my auth.ts file, I included the role property in the session object and enc ...

Issue with retrieving all phone numbers from a contact in Ionic

Hope you're doing well! I'm encountering an issue with Ionic Contacts. Currently, I'm able to retrieve all the contacts using my code but I need help extracting all the phone numbers associated with each contact. For example, if John has 3 ...

Adjusting characteristics in Angular dynamically through JSON

Having trouble changing the value of [icon]="reactAtom" to use a JSON value? Need assistance in updating the [icon] value based on the 'featureItem' received from the parent component. HTML <div> <fa-icon [icon]="reactAtom" class="i ...

Tips for executing numerous asynchronous tasks in Ionic 3 and closing a loader once all tasks are completed

Currently, I am in the process of developing an Ionic 3 application that offers the feature to cache a list of articles content on demand. The implementation involves utilizing Storage which employs promises for its operations. The code snippet I have wri ...

How can I suggest the return type of a function that is out of my control?

When I attempt to parse a JSON-formatted string, a linter error is triggered: let mqttMessage = JSON.parse(message.toString()) // ESLint: Unsafe assignment of an `any` value. (@typescript-eslint/no-unsafe-assignment) Given that I am in control of the con ...

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...

The specified type '{ songs: any; }' cannot be assigned to the type 'IntrinsicAttributes' in NEXTJS/Typescript

I am currently working on a straightforward script. Below is the index.tsx file for my Next.js application: import type { NextPage } from 'next' import SongsList from '../components/SongsList/SongsList' import { GetStaticProps } from & ...