❮ Table of contents

Type checked unique arrays

Note: This applies to TypeScript 4.1 and later

According to Wikipedia, a set is a well-defined collection of distinct (unique) objects. We've already got a Set type in JavaScript enforcing this at runtime, but to have TypeScript do the same, we'll have to use arrays declared as const, as opposed to ordinary arrays. Hover the two variables to see how TypeScript infers their type.

Declaring arrays as const enables us to write types that deal with each element in the array. Let's start out by creating a type that is either true or false depending on whether or not X is in array T.

Now that we're able to see if something is in an array, we can write a UniqueArray<T> type.

If a duplicate is found, an array is returned with an error message. In TS 4.1, we don't have a way of returning better error messages, but I suspect this will get implemented in later versions.

I don't know why you'd use this, I wrote it after stumbling upon a Stack Overflow question.