#Unique array type

20 messages · Page 1 of 1 (latest)

brazen thunder
#

I have a readonly array of IDs, and I am trying to write a type UniqueArray which would return the original array type if the are no repeated values, and never otherwise. I have tried different ways of creating such a type but had no success.

I hope someone who understands TypeScript better than me would be willing to help.

Reproduction below (noop).

loud flameBOT
#
deminearchiver#0

Preview:```ts
// T if the array contains only unique strings, never otherwise
type UniqueArray<T extends readonly string[]> = T;

declare const ids1: ["one", "two", "three", "four", "five"];
declare const case1: UniqueArray<typeof ids1> // typeof ids1

declare const ids2: ["one", "one", "three", "two"];
...```

worn sluice
#

i can think of a somewhat cursed way

#

!:u2t

loud flameBOT
#
joshcena63#0
type U2I<U> = (
  U extends U ? (arg: U) => 0 : never
) extends (arg: infer I) => 0
  ? I
  : never

// For homogeneous unions, it picks the last member
type OneOf<U> = U2I<
  U extends U ? (x: U) => 0 : never
> extends (x: infer L) => 0
  ? L
  : never

type U2T<U, L = OneOf<U>> = [U] extends [never]
  ? []
  : [...U2T<Exclude<U, L>>, L]```
#
that_guy977#0

Preview:```ts
...
type UniqueArray<T extends readonly string[]> = U2T<
T[number]

["length"] extends T["length"]
? T
: never
...```

worn sluice
#

maybe the other way around could be better to handle unions inside the array

brazen thunder
#

I don't even understand what the first one does

#

that's so cursed

worn sluice
#

U2T = union to tuple
U2I = union to intersection

brazen thunder
#

What's up with those function types?

worn sluice
#

even though it's possible to a degree with this, it still wouldn't handle cases where the array isn't fully known, which could come up in practice
this is something better left for the runtime to deal with

brazen thunder
#

It is fully known as far as I'm aware

#

Thank you so much for a quick answer!

brazen thunder
#

!resolved

brazen thunder
compact holly
#

I read the question

worn sluice
brazen thunder
#

The project is too complex to give any context