-1

I am looking for something like Set but with just a compile-time check possibly with Array interface, consider this:

const arr = Unique<string[]>['x','y','z']
if(arr.includes('x')){...}

Now I want TS compiler errors on this, saying, duplicate values are not allowed:

 const arr = Unique<string[]>['x','x','z']
 if(arr.includes('x')){...}

Any idea?

mehran
  • 1,314
  • 4
  • 19
  • 33
  • Why not use a set? Enforcing unique identity among elements is its purpose. – jsejcksn Jan 09 '23 at 03:43
  • @jsejcksn I don't want/need runtime check, the list is static and provided at compile time. Also, I would like to have Array interface like `includes` method. – mehran Jan 09 '23 at 03:45
  • 1
    AFAIK this is not possible with an array type: the compiler will require a [tuple](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) to be able to evaluate the type of each element. Are you aware of [`Set.prototype.has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has)? – jsejcksn Jan 09 '23 at 03:46
  • 1
    Does this answer your question? https://stackoverflow.com/questions/57016728/is-there-a-way-to-define-type-for-array-with-unique-items-in-typescript – Alex Wayne Jan 09 '23 at 03:50
  • 1
    There's no specific type that works that way, but you can write a generic helper function that tries to enforce uniqueness. Does [this approach](https://tsplay.dev/weB3YN) meet your needs? – jcalz Jan 09 '23 at 04:11

1 Answers1

0

You can declare unique array types like so:

  type UniqueArrType = ["x", "y", "z"];

  const arr: UniqueArrType = ["x", "y", "z"];

It will error out on incorrect values

  type UniqueArrType = ["x", "y", "z"];

  const arr: UniqueArrType = ["y", "y", "z"];
  // Error: Type '"y"' is not assignable to type '"x"'.
  • 3
    Presumably the OP wants to *accept* `["z", "y", "x"]`, or any array with no duplicates – jcalz Jan 09 '23 at 04:06