Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: remove key from type/subtraction type

I want to define a generic type ExcludeCart<T> that is essentially T but with a given key (in my case, cart) removed. So, for instance, ExcludeCart<{foo: number, bar: string, cart: number}> would be {foo: number, bar: string}. Is there a way to do this in TypeScript?

Here's why I want to do this, in case I'm barking up the wrong tree: I'm converting an existing JavaScript codebase to TypeScript, which contains a decorator function called cartify that takes a React component class Inner and returns another component class Wrapper.

Inner should take a cart prop, and zero or more other props. Wrapper accepts a cartClient prop (which is used to generate the cart prop to pass to Inner), and any prop that Inner accepts, except cart.

In other words, once I can figure out how to define ExcludeCart, I want to do this with it:

function cartify<P extends {cart: any}>(Inner: ComponentClass<P>) : ComponentClass<ExcludeCart<P> & {cartClient: any}> 
like image 467
Leigh Brenecki Avatar asked Jan 05 '17 01:01

Leigh Brenecki


1 Answers

Update for TypeScript 3.5: The Omit<Type, Keys> utility type is now available. Please see Mathias' answer for an example usage.


Old Answer: Since TypeScript 2.8 and the introduction of Exclude, It's now possible to write this as follows:

type Without<T, K> = {     [L in Exclude<keyof T, K>]: T[L] }; 

Or alternatively, and more concisely, as:

type Without<T, K> = Pick<T, Exclude<keyof T, K>>; 

For your usage, you could now write the following:

type ExcludeCart<T> = Without<T, "cart">; 
like image 93
alter_igel Avatar answered Oct 05 '22 17:10

alter_igel