我正在尝试为Array创建扩展方法。
这是我创建的:
interface Array<T> {
moveServiceBranchInArray(): void;
}
Array.prototype.moveServiceBranchInArray = function<T> (array: T[], pred: (x: T) => boolean, index: number): void
{
const curPos: number = array.findIndex(pred);
index = Math.max(Math.min(index, array.length - 1), 0);
if (curPos < 0) {
return;
}
[array[curPos], array[index]] = [array[index], array[curPos]];
}
不幸的是我遇到了错误
“类型 '((array:T [],pred:(x:T)=>布尔值,索引:数字)=> void'不能分配给'()=> void'类型。”
如标题所示。什么给,帮助赞赏。
答案 0 :(得分:2)
您的接口有一个不带参数的方法,因此没有() => void
,但是在实现中您会得到一些参数,尤其是带有签名(array: T[], pred: (x: T) => boolean, index: number) => void
的
这正是编译器试图告诉您的。
修复接口以使其与您的实现相匹配应该足够。
答案 1 :(得分:0)
您应该像这样在界面中指定函数参数:
interface Array<T> {
moveServiceBranchInArray(array: T[], pred: (x: T) => boolean, index: number): void;
}
Array.prototype.moveServiceBranchInArray = function<T> (array: T[], pred: (x: T) => boolean, index: number): void
{
const curPos: number = array.findIndex(pred);
index = Math.max(Math.min(index, array.length - 1), 0);
if (curPos < 0) {
return;
}
[array[curPos], array[index]] = [array[index], array[curPos]];
}