Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to define type for array with unique items in typescript?

The type should detect if the array has duplicate items and throw error in typescript?

type UniqueArray = [
  // How to implement this?
]

const a:UniqueArray = [1, 2, 3] // success
const b:UniqueArray = [1, 2, 2] // error

PS: I'am currently removing duplicate items using JS, but, curious if this error can be captured using typescript type before hand?

like image 550
Ganapati V S Avatar asked Jul 13 '19 06:07

Ganapati V S


People also ask

How do you define a type of array in TypeScript?

In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.


1 Answers

Yes! There is a way with TypeScript 4.1 (in beta at the time of writing). This is how:

const data = ["11", "test", "tes", "1", "testing"] as const
const uniqueData: UniqueArray<typeof data> = data

type UniqueArray<T> =
  T extends readonly [infer X, ...infer Rest]
    ? InArray<Rest, X> extends true
      ? ['Encountered value with duplicates:', X]
      : readonly [X, ...UniqueArray<Rest>]
    : T

type InArray<T, X> =
  T extends readonly [X, ...infer _Rest]
    ? true
    : T extends readonly [X]
      ? true
      : T extends readonly [infer _, ...infer Rest]
        ? InArray<Rest, X>
        : false

You'll get a compiler error if the same value occurs more than once.

Here's my article describing things in better detail.

Try in TypeScript Playground

like image 56
Jan Sommer Avatar answered Sep 19 '22 23:09

Jan Sommer