Search code examples
typescripttypestypescript-typingstypescript-types

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?


Solution

  • 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