如何为变量分配未参数化的泛型函数?
在下面的示例中,考虑通过组合泛型函数并将合成结果分配给变量来考虑创建areArraysShallowlyEqual
函数的尝试:
export function areNullablesEqualOver<a>(areEqual: (one: a, another: a) => boolean)
:(one: a, another: a) => boolean {
return function(one, another) {
if (one == null) {
if (another == null) {
return true;
} else {
return false;
}
} else {
if (another == null) {
return false;
} else {
return areEqual(one, another);
}
}
};
};
export function areArraysEqualOver<a>(areEqual: (one: a, another: a) => boolean)
: (one: a[], another: a[]) => boolean {
return function (ones, anothers) {
var length = ones.length;
if (length !== anothers.length) return false;
for (var index = 0; index < length; index++) {
if (areEqual(ones[index], anothers[index])) continue;
return false;
}
return true;
}
}
export function areSame<a>(one: a, another: a): boolean {
return one === another;
}
// PROBLEM:
export var areArraysShallowlyEqual<a> = areNullablesEqualOver<a>(areArraysEqualOver(areSame));
答案 0 :(得分:1)
您可以使用泛型类来完成此操作。这与您正在执行的操作不完全相同,因为您需要使用类型参数实例化类,而不是将类型参数传递给单个函数 - 但是您不能将类型参数传递给您建议的变量实施是不可能的。
接口不是必需的,您可以在整个过程中重复类型注释,但它们有助于区分数组和非数组变体。
areArraysEqualOver
和areNullablesEqualOver
已在areArraysShallowlyEqual
属性中交换 - 这是因为areArraysEqualOver
方法未返回与其他签名兼容的类型,因为它返回一个数组比较器,所有其他方法接受一个非数组比较器。
interface EqualityFunction<T> {
(one: T, another: T) : boolean;
}
interface ArrayEqualityFunction<T> {
(one: T[], another: T[]) : boolean;
}
class Example<a> {
areNullablesEqualOver(areEqual: EqualityFunction<a>) : EqualityFunction<a> {
return function(one, another) {
if (one == null) {
if (another == null) {
return true;
} else {
return false;
}
} else {
if (another == null) {
return false;
} else {
return areEqual(one, another);
}
}
};
}
areArraysEqualOver(areEqual: EqualityFunction<a>) : ArrayEqualityFunction<a> {
return function (ones, anothers) {
var length = ones.length;
if (length !== anothers.length) return false;
for (var index = 0; index < length; index++) {
if (areEqual(ones[index], anothers[index])) continue;
return false;
}
return true;
}
}
areSame(one: a, another: a): boolean {
return one === another;
}
areArraysShallowlyEqual = this.areArraysEqualOver(this.areNullablesEqualOver(this.areSame));
}
调用代码如下所示:
var example = new Example<string>();
example.areArraysShallowlyEqual(['a', 'b'], ['a', 'b']); // true
example.areArraysShallowlyEqual(['a', 'b'], ['a', 'c']); // false