Grab that Item-array and change it!

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

Aart den Braber
3 min readJan 11, 2021

--

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:

A partial solution — but is it good enough? I think not.

😓 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).

type PickRedefine<T, Includes extends keyof T, Redefines extends keyof T> =
Pick<T, Includes>
& {
// add the properties to redefine as 'unknown' - they have to be redefined
[R in Redefines]: unknown;
};

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

This error is a good thing!

As you can see when hovering:

It explains a clear, descriptive problem, just like you’d expect

And it will be satisfied when you add that again

And the error is gone ✨

Features

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

Throws TS-errors when the interfaces change

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!

https://stackblitz.com/edit/destructuring-to-array-to-object

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

--

--

Aart den Braber

Software developer with a passion for beautiful code