有没有办法在打字稿中为具有唯一项的数组定义类型? [英] 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:我目前正在使用 JS 删除重复项,但是,好奇是否可以事先使用 typescript 类型捕获此错误?
PS: I'am currently removing duplicate items using JS, but, curious if this error can be captured using typescript type before hand?
推荐答案
是的!TypeScript 4.1(在撰写本文时处于测试阶段)有一种方法.方法如下:
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.
这篇关于有没有办法在打字稿中为具有唯一项的数组定义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文