错误 TS2365:运算符“+”不能应用于类型“{}”和 'number'
error TS2365: Operator '+' cannot be applied to types '{}' and 'number'
我正在使用 TypeScript 2.x 和 lodash。
当我使用
console.log(_.reduce([1, 2], (result, n) => result + n)); // 3
它给我错误:
error TS2365: Operator '+' cannot be applied to types '{}' and
'number'.
更改为 result: number
将解决问题。
console.log(_.reduce([1, 2], (result: number, n) => result + n)); // 3
TypeScript 只能知道 n
是基于 [1, 2]
的数字。但是它不知道 returns 之前的 result
的类型。所以你需要明确地告诉它。
例如,
console.log(_.reduce([1, 2], (result, n) => 'hi')); // 'hi'
result
的类型是字符串而不是数字。
我正在使用 TypeScript 2.x 和 lodash。
当我使用
console.log(_.reduce([1, 2], (result, n) => result + n)); // 3
它给我错误:
error TS2365: Operator '+' cannot be applied to types '{}' and 'number'.
更改为 result: number
将解决问题。
console.log(_.reduce([1, 2], (result: number, n) => result + n)); // 3
TypeScript 只能知道 n
是基于 [1, 2]
的数字。但是它不知道 returns 之前的 result
的类型。所以你需要明确地告诉它。
例如,
console.log(_.reduce([1, 2], (result, n) => 'hi')); // 'hi'
result
的类型是字符串而不是数字。