这是使用重载函数作为通用高阶函数的等式约束的简单尝试:
function eq(x: boolean, y: boolean): boolean;
function eq(x: number, y: number): boolean;
function eq(x: string, y: string): boolean;
function eq(x: any, y: any) { return x === y };
const arrEq = <A>(eq: (x: A, y: A) => boolean) => (xs: A[]) => (ys: A[]) => {
const go = (b: boolean, i: number): boolean =>
b === false ? false
: i === xs.length ? true
: go(eq(xs[i], ys[i]), i + 1);
return go(true, 0)
};
arrEq(eq) ([1, 2, 3]) ([1, 2, 3]); // A
在行A
中,类型变量A
被推断为string
,这似乎很随意。我怎样才能解决这个问题?