我想编写一个给定数组的函数,从中删除重复的元素。我希望这个函数至少可以用于数字和字符串。我的尝试是:
function removeDuplicates<T>(xs: T[]): T[]
{
var res: T[] = [];
var seen = {};
for (var i = 0; i < xs.length; i++) {
var x = xs[i];
if (!(x in seen)) {
seen[x] = null;
res.push(xs[i]);
}
}
return res;
}
哪个是有效的Javascript用于删除元素(删除类型后)。但是,在TypeScript中,我在in
行上收到错误消息:
'in'表达式的左侧必须是'any','string','number'或'symbol'类型。
我尝试了T extends string | number
,但这不起作用。我考虑过T is string | number
,但我找不到任何TypeScript语法。如何在类型中捕获此属性?
答案 0 :(得分:3)
一种解决方案是使用显式类型注释any
:
function removeDuplicates<T>(xs: T[]): T[]
{
var res: T[] = [];
var seen = {};
for (var i = 0; i < xs.length; i++) {
var x:any = xs[i];
if (!(x in seen)) {
seen[x] = null;
res.push(xs[i]);
}
}
return res;
}
我还建议明确应用string|number
约束:
type ValidKey = string|number;
function removeDuplicates<T extends ValidKey>(xs: T[]): T[]
{
var res: T[] = [];
var seen = {};
for (var i = 0; i < xs.length; i++) {
var x:ValidKey = xs[i];
if (!(x in seen)) {
seen[x] = null;
res.push(xs[i]);
}
}
return res;
}
removeDuplicates(['a','b','a']) // okay
removeDuplicates([1,2]) // okay
removeDuplicates([{a:1},{a:2}]) // Not cool