-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Labels
BugA bug in TypeScriptA bug in TypeScriptFixedA PR has been merged for this issueA PR has been merged for this issue
Milestone
Description
I'm trying to rewrite the signature of sum
from core.ts
in our compiler (see #16823), but I'm getting this error:
export function sum<T extends Record<K, number>, K extends string>(array: T[], prop: K): number {
let result = 0;
for (const v of array) {
result += v[prop];
// ~~~~~~~~~~~~~~~~~
// Operator '+=' cannot be applied to types 'number' and 'T[K]'.
}
return result;
}
Note that I can't declare sum
as
export function sum<K extends string>(array: Record<K, number>[], prop: K): number
because then TypeScript would infer all of the properties in each element for K
. So I do need another type argument T
for the indirection.
For a simpler repro:
function foo<T extends number>(x: T) {
return 0 + x;
// ~~~~~
// Operator '+' cannot be applied to types '0' and 'T'.
}
Related is #15645.
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFixedA PR has been merged for this issueA PR has been merged for this issue