运算符“+”不能应用于类型 'Number' 和 'Number'。为什么?
Operator '+' cannot be applied to types 'Number' and 'Number'. Why?
我正在尝试创建一个简单的函数来查找给定数组中最小的两个整数。打字稿的新手,但很好用 Javascript,我想知道为什么打字稿会抱怨添加两个数字:
const array: Number[] = [
2, 3, 4, 2, 4, 3, 5, 2, 5, 91, 2, 4, 32, 43, 3, 5, 3435,
];
const twoSmallest = (array: Number[]): Number[] => {
if (array.length < 2) return array;
const maxSum = array.reduce((acc: Number, curr: Number):Number => {
return curr + acc;
}, 0);
for (let i = 0; i < array.length; i++) {
//About to add my rest of the code here
}
};
console.log('Result = ', twoSmallest(array));
Number
是使用 Number
构造函数创建的东西的类型,例如
const someNum = new Number(123);
它有 odd repercussions 并且几乎不应该被使用。
对于纯数字 - 99% 的时间应该使用哪个数字 - 你只需要 number
,例如
const array: number[] = [
2, 3, 4, 2, 4, 3, 5, 2, 5, 91, 2, 4, 32, 43, 3, 5, 3435,
];
将您所有的 Number
替换为 number
,它将按预期工作。
您也可以在不需要时删除显式注释,TypeScript 会为您推断它们 - 手动注释越少意味着意外输入错误的可能性越小。
我正在尝试创建一个简单的函数来查找给定数组中最小的两个整数。打字稿的新手,但很好用 Javascript,我想知道为什么打字稿会抱怨添加两个数字:
const array: Number[] = [
2, 3, 4, 2, 4, 3, 5, 2, 5, 91, 2, 4, 32, 43, 3, 5, 3435,
];
const twoSmallest = (array: Number[]): Number[] => {
if (array.length < 2) return array;
const maxSum = array.reduce((acc: Number, curr: Number):Number => {
return curr + acc;
}, 0);
for (let i = 0; i < array.length; i++) {
//About to add my rest of the code here
}
};
console.log('Result = ', twoSmallest(array));
Number
是使用 Number
构造函数创建的东西的类型,例如
const someNum = new Number(123);
它有 odd repercussions 并且几乎不应该被使用。
对于纯数字 - 99% 的时间应该使用哪个数字 - 你只需要 number
,例如
const array: number[] = [
2, 3, 4, 2, 4, 3, 5, 2, 5, 91, 2, 4, 32, 43, 3, 5, 3435,
];
将您所有的 Number
替换为 number
,它将按预期工作。
您也可以在不需要时删除显式注释,TypeScript 会为您推断它们 - 手动注释越少意味着意外输入错误的可能性越小。