60

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}>
Adrian Leonhard
  • 7,040
  • 2
  • 24
  • 38
Daisy Leigh Brenecki
  • 7,571
  • 6
  • 28
  • 43
  • 1
    Not yet, but there's a suggestion - https://github.com/Microsoft/TypeScript/issues/4183. See also https://github.com/Microsoft/TypeScript/issues/12215 – artem Jan 05 '17 at 01:53

7 Answers7

86

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">;
alter_igel
  • 6,899
  • 3
  • 21
  • 40
  • This works pretty good. One thing I noticed was that if `T` has types that are optional, after using `Without` they are all required. Do you know why that is? – Henrik R Jul 06 '18 at 07:27
  • 7
    The docs also mention that `type Omit = Pick>` will also work, [in the 2.8 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#predefined-conditional-types) (down the bottom of the linked section). This version of `Omit` seems to work as expected with optional members too. – Daisy Leigh Brenecki Aug 09 '18 at 06:10
  • This is a good answer, I couldn't figure out how to scale it to multiple keys. [I took an attempt at a more direct use of exclude in another answer.](https://stackoverflow.com/a/58242538/20774) That approach scales rather easily. – James McMahon Oct 04 '19 at 20:05
67

While this has been correctly answered, I wanted to point out that TypeScript 3.5 did add an Omit<T, E> type.

type NoCart = Omit<{foo: string, bar: string, cart: number}, "cart">;

This results in the {foo: string, bar: string} type.

Mathias
  • 2,484
  • 1
  • 19
  • 17
14

While there isn't a built-in subtraction type, you can currently hack it in:

type Sub0<
    O extends string,
    D extends string,
> = {[K in O]: (Record<D, never> & Record<string, K>)[K]}

type Sub<
    O extends string,
    D extends string,
    // issue 16018
    Foo extends Sub0<O, D> = Sub0<O, D>
> = Foo[O]

type Omit<
    O,
    D extends string,
    // issue 16018
    Foo extends Sub0<keyof O, D> = Sub0<keyof O, D>
> = Pick<O, Foo[keyof O]>

In the question's case, you would do:

type ExcludeCart<T> = Omit<T, 'cart'>

With TypeScript >= 2.6, you can simplify it to:

/**
 * for literal unions
 * @example Sub<'Y' | 'X', 'X'> // === 'Y'
 */
export type Sub<
    O extends string,
    D extends string
    > = {[K in O]: (Record<D, never> & Record<string, K>)[K]}[O]

/**
 * Remove the keys represented by the string union type D from the object type O.
 *
 * @example Omit<{a: number, b: string}, 'a'> // === {b: string}
 * @example Omit<{a: number, b: string}, keyof {a: number}> // === {b: string}
 */
export type Omit<O, D extends string> = Pick<O, Sub<keyof O, D>>

test it on the playground

Adrian Leonhard
  • 7,040
  • 2
  • 24
  • 38
  • This is great, thanks! All of the previous implementations of `Omit` that I'd tried didn't work on generics, but these ones do. – Daisy Leigh Brenecki Dec 05 '17 at 02:02
  • Very cool! Adrian, did you develop this, or did you find it somewhere else? If it's from somewhere else, can you link to that source? I was trying to look into your answer to see if it had any limitations or any other relevant discussion about it. I've also linked to your answer from mine because it seems to work well – JKillian Dec 05 '17 at 15:00
  • 1
    @JKillian no, I can't remember where I got it from, but various variants are discussed on the corresponding TS issue, for example https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458 – Adrian Leonhard Dec 05 '17 at 17:52
  • I remember going through that exact thread and trying all the variants there around the time I posted this question, and all of the ones I tried didn't work for generics (as in, you could go `Omit` where `T` was some concrete type, but something like `function myfunc(in: T) : Omit` would break with rather confusing errors). So I'm not sure if it's a different way of defining `Omit` that popped up later or an improvement/bugfix in TS, but I think your answer was correct at the time it was posted, @JKillian :) – Daisy Leigh Brenecki Dec 11 '17 at 05:40
2

there is another very simple way to have this result

When combining type in typescript, the type "never" have higher priority to everything.

You can simply create a type:

type noCart<T> = T & {cart : never}

Or, without creating type

function removeCart<T>(obj : T) : T & {cart : never} {
    if("cart" in obj) {
        delete (obj as T & {cart : any}).cart;
    }
    return <T & {cart : never}> obj;
}

This is less generic than the solution of Adrian, but a bit simpler when we don't need the complexity.

Félix Brunet
  • 1,993
  • 1
  • 18
  • 22
1

Update: See Adrian's answer above for a solution to this question. I've left my answer here though since it still contains some useful links.


There are various old requests for this feature ("outersection" types, subtraction types), but none have really progressed.

Recently, with the addition of mapped types I asked about this again, and Anders said that while there's no plans to make a general subtraction type operator, a more limited version might be implemented, presumably looking something like this proposal.

I've personally run into quite similar situations to you when working with React, and unfortunately haven't been able to find any good solution. In a simple case, you can get away with something like:

interface BaseProps {
    foo: number;
    bar: number;
}

interface Inner extends BaseProps {
    cart: Cart;
}

interface Wrapper extends BaseProps {
    cartClient: Client;
}

but I almost find this to be a semantic abuse of the extends keyword. And of course, if you don't control the typings of Inner or BaseProps, then this won't work out.

JKillian
  • 18,061
  • 8
  • 41
  • 74
  • 1
    Thanks for that! Unfortunately I can't really do what you're suggesting, because I want to be able to just type `MyComponent = cartify(MyComponent)` (or `@cartify↵class MyComponent…` once that syntax lands) and have TypeScript automatically infer the correct type for the wrapped component. And it's a reusable library, so I definitely can't predict `Inner` ahead of time either. – Daisy Leigh Brenecki Jan 05 '17 at 05:23
0

So, for instance, ExcludeCart<{foo: number, bar: string, cart: number}> would be {foo: number, bar: string}

You can use the Exclude syntax to do this directly:

Exclude<{foo: number, bar: string, cart: number}, { cart: number}>
James McMahon
  • 48,506
  • 64
  • 207
  • 283
  • I believe simply `Exclude<{ foo: number, bar: string, cart: number }, "cart">` will do the trick. – Mathias Oct 08 '19 at 05:55
  • You're right! I was thinking `Omit<{foo: number, bar: string, card: number}, "cart">` which achieves the correct result. Again. thanks for double checking! Should I delete the comment above? – Mathias Oct 21 '19 at 04:42
  • Oh neat. I will have to try that out. Up to you on the comment. – James McMahon Oct 23 '19 at 04:31
0

Probably all the answers are correct, but I built a shorter Subtract generic which does what you need:

type Subtract<T extends K, K> = Omit<T, keyof K>;
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83