NodeJS 如何在数组中显示重复的错误,仅在TypeScript中[重复]

tvokkenx  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(145)

此问题在此处已有答案

Is there a way to define type for array with unique items in typescript?(8个答案)
7天前关闭

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']

字符串
我想找到自定义类型,我希望看到重复的错误

ht4b089n

ht4b089n1#

假设你想在运行时检查它,你可以使用下面的这个函数:

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

字符串
然后用你的测试值调用它:

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


如果你要求在编译时测试它,我不认为TS中有办法做到这一点,只有在运行时。

相关问题