面试题答案
一键面试class FunctionWrapper<A = string, B = number> {
private fn: (arg: A) => B;
constructor(fn: (arg: A) => B) {
this.fn = fn;
}
execute(arg: A): B {
return this.fn(arg);
}
}
// 类型约束说明:
// 1. 为 A 设置默认类型 string,为 B 设置默认类型 number。
// 2. 当 A 为 string 类型时,B 只能是 number 或 string。
// 3. 当 A 为 number 类型时,B 只能是 boolean。
// 逆变协变体现:
// 在函数类型 (arg: A) => B 中,参数位置 A 体现逆变(因为函数参数类型允许更宽泛类型传入),返回值位置 B 体现协变(因为函数返回值类型必须与声明一致或更具体)。