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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With