Skip to content

Unable to add numeric types that are not simply 'number' #17069

@DanielRosenwasser

Description

@DanielRosenwasser

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 TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions