面试题答案
一键面试interface MathOperation {
(num1: number, num2: number): string | number;
}
const performMathOperation: MathOperation = (num1, num2) => {
if (num1 % 2 === 0) {
return `result is even`;
} else {
return num1 * num2;
}
};
在上述代码中:
- 首先定义了接口
MathOperation
,它接受两个number
类型参数,返回值类型为string | number
,具体返回类型取决于第一个参数是否为偶数。 - 然后实现了
performMathOperation
函数,该函数符合MathOperation
接口的调用签名。函数内部通过判断第一个参数是否为偶数,来决定返回字符串类型还是数字类型的结果。