0
type MyType = ('t' | 'd' | 's')[]

// This will work without problem
const value: MyType = ['t', 'd']

// I expect an error from this code, because it has duplicates in it
const value: MyType = ['t', 't']

I would like to find custom type, where I expect to see an error for duplicates

Samculo
  • 89
  • 3
  • 1
    You could list all allowed combinations: `type My type = ['t', 'd'] | ['t', 's'] | ...` – jabaa Jul 27 '23 at 16:35

1 Answers1

-1

Assuming you want to check it at runtime, you can use this function below:

function hasDuplicates<T>(array: T[]): boolean {
    return new Set(array).size !== array.length;
}

and then calling it with your test values:

const value1: MyType = ['t', 'd'];
console.log(hasDuplicates(value1));
    
const value2: MyType = ['t', 't'];
console.log(hasDuplicates(value2));

In case you asked to test it at transpile time, I don't think there is a way in TS to do that, only at runtime.

Marc
  • 2,183
  • 2
  • 11
  • 16