Is it possible for lodash's omit function to return a specific type instead of just a partial type?

Within the following code snippet:

import omit from "lodash/fp/omit";

type EnhancerProps = {
  serializedSvg: string;
  svgSourceId: string;
  containerId: string;
};

const rest = omit(["serializedSvg", "containerId"])(props);

The variable 'rest' is currently typed as Partial. Is there a way to customize the return value of omit, so that it specifically returns {svgSourceId: string} instead?

Answer №1

It's interesting how omit doesn't automatically infer types by itself. I'm not sure why that is, but I've devised a helper function that should solve the issue.

function omitWithTypes<A extends ReadonlyArray<keyof B>, B extends Object>(
  typeArray: A,
  obj: B
) {
  return omit(typeArray)(obj) as Omit<B, A[number]>;
}

The Omit utility type enables you to specify properties of a type. However, if you need to transform array values into a union type and pass them to Omit, the array must be read-only. You can achieve this by using the as const assertion to inform the TS compiler that it won't change.

const filter = ["serializedSvg", "svgSourceId"] as const;
const exclusive = omitWithTypes(filter, props);

OR

const exclusive = omitWithTypes(["serializedSvg", "svgSourceId"] as const, props);

You'll receive accurate inferred types (although it may seem a bit lengthy as it employs the Pick utility type in the background):

https://i.sstatic.net/XqO2c.png

If you attempt to exclude values that aren't object properties, an error will arise:

https://i.sstatic.net/PPW6Y.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

How come TypeScript does not detect when a constant is used prior to being assigned?

There's an interesting scenario I came across where TypeScript (3.5.1) seems to approve of the code, but it throws an error as soon as it is executed. It appears that the root cause lies in the fact that value is being declared without being initiali ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...

Troubleshooting React TypeScript in Visual Studio Code

I've recently set up an ASP Core project with the React TypeScript template, but I'm encountering difficulties when it comes to debugging. The transition between the TypeScript code and the corresponding generated JavaScript code is proving to be ...

Is there a different option similar to forkJoin for handling incomplete observables?

constructor( private route: ActivatedRoute, private http: Http ){ // Retrieve parameter changes observable let paramObs = route.paramMap; // Fetch data once only let dataObs = http.get('...'); // Subscribe to both ob ...

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

Exploring Objects using Typescript

I need help creating a mapper for objects that allows TypeScript to recognize the returned type correctly. For example: type ExampleObject = { text: string; // this object may have properties of any type number: number; }; const object: ExampleObjec ...

Determine whether or not there are any duplicate elements within an array object

Is there a way to determine true or false if there are any duplicates within an object array? arr = [ { nr:10, name: 'aba' }, { nr:11, name: 'cba' }, { nr:10, name: 'aba' } ] arr2 = [ { year:2020, cit ...

What is the proper way to address the error message regarding requestAnimationFrame exceeding the permitted time limit?

My Angular application is quite complex and relies heavily on pure cesium. Upon startup, I am encountering numerous warnings such as: Violation ‘requestAnimationFrame’ handler took 742ms. Violation ‘load’ handler took 80ms. I attempted to resolve ...

Invoking a controller from another controller in the Express framework using Typescript

Currently, I am trying to call a controller from another controller in my code. While attempting to pass parameters using {params: {task_id: String(task_id), result}}, TypeScript is flagging an error indicating that res does not have all the required attri ...

Best practices for implementing "Event Sourcing" in the NestJS CQRS recipe

I've been exploring the best practices for implementing "Event Sourcing" with the NestJS CQRS recipe (https://docs.nestjs.com/recipes/cqrs). After spending time delving into the features of NestJS, I have found it to be a fantastic framework overall. ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

Tips for adjusting the time format within Ionic 3 using TypeScript

I currently have a time displayed as 15:12:00 (HH:MM:SS) format. I am looking to convert this into the (3.12 PM) format. <p class="headings" display-format="HH:mm" > <b>Time :</b> {{this.starttime}} </p> In my TypeScript code t ...

Is there a way to subscribe to various observables simultaneously in Angular 2, and then pause until fresh data is available on each of them?

I have an Angular component that relies on 3 services, each of which has an observer I can subscribe to. The view of the component needs to be updated whenever there are changes in the observed data, which occurs through websockets (feathers.js). I want th ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

Why does isDisplayed method in Protractor return "No element found using locator" instead of a boolean value?

In my code, I've created a function called isElementDisplayed which features a call to element.isDisplayed. I'm curious as to why the isDisplayed method sometimes returns No element found instead of a boolean value. isElementDisplayed(element: ...

Determine the sum of exported identifiers based on ESLint rules

Currently, I am facing a requirement in my JavaScript/TypeScript monorepo to ensure that each library maintains a minimal amount of exported identifiers. Is there any existing eslint rule or package available that can keep track of the total number of exp ...

All components load successfully except for the worker in Webpack

I've been working on configuring webpack to bundle my react project. I successfully set up the webpack_public_path variable and all modules are loading correctly, except for the worker. const path = require('path'); const MonacoWebpackPlugi ...

Using React TypeScript to trigger a function upon route changes with react-router-dom

I am trying to use the useEffect hook to console log every time the location changes in my project. However, when I try to compile, I receive an error in the terminal saying Unexpected use of 'location' no-restricted-globals. I would like to fin ...

Prevent users from clicking buttons until all mandatory fields are filled out using react-hook-form

I am seeking guidance on how to dynamically disable a button based on the input values of both Name and State in the given code snippet. Specifically, I want to restrict button functionality until both name and state fields are filled out, regardless of ...