Grab that Item-array and change it!

Pick one instance of a TypeScript array — destructuring [] to {}

If you are in the rare pickle of having to destructure a TS-array to a single instance, here is what I think could help you. First, I’ll explain the problem.

Imagine an interface called `Order`. It’s defined like this:

Now, you have decided that, if you create an Order, you just want to define the name and the price of the items. How will you do that?

If you just want to define the name of the Order (or id, for that matter), you can use TypeScript’s Pick-type, like so:

😓 Picking a single object in an array

Now for something a bit harder, which cost me significant time researching. You have an `items`-array in the `Order`-interface. This array consists of `Item`-objects. What if you want to use just the `name` and `price` from that `Item`-object? You can’t do something like `items[price, value]`, because you’ll get an error:

Solution: create a new TS-type

So how then can we change that pesky `Order.items`-property? I have tried multiple solutions, but believe me: you can’t destructure `Item[]` to just get the `Item` and change it (at least: I haven’t found it). You will have to overwrite the `Order.items`-property. So if you want `Order[name, items]` where the `Item`-interface just requires `name` and `price`, you can write it down like this, using the PickRedefine type you can find below.

For me, the solution was to create a new type. This would have to allow you to `Pick` some properties, but allow you to redefine some properties as well (or actually: require).

This little snippet will help you when creating a new `Order`. Here, it’s complaining that you didn’t declare the `name`-prop.

As you can see when hovering:

And it will be satisfied when you add that again


This little snippet will warn you when you will change the `Item`-interface, for example when its `price`-prop will change to `priceInEur`.

If you forget to redefine the property, IntelliSense won’t help you. So you’ll know something is wrong pretty soon.

There’s a lot more to it, but that’s perhaps better explained by doing than by reading. So here is a StackBlitz playground to check out!

Tags: TypeScript pick array, pick single instance, pick single child property (or object) from array interface

Software developer with a passion for beautiful code