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.

Activity

changed the title [-]Unable to add types constrained to 'number'[/-] [+]Unable to add types that are not simply 'number'[/+] on Jul 10, 2017
changed the title [-]Unable to add types that are not simply 'number'[/-] [+]Unable to add numeric types that are not simply 'number'[/+] on Jul 10, 2017
ghost

ghost commented on Jul 10, 2017

@ghost

Related: #15501

added a commit that references this issue on Aug 17, 2017
b8e0ded
sandersn

sandersn commented on Aug 17, 2017

@sandersn
Member

Fix is up at #17870

sandersn

sandersn commented on Aug 17, 2017

@sandersn
Member

Note that #17404 fixed the simpler repro; #17870 fixes the original issue with a type parameter indexed by another type parameter.

added
FixedA PR has been merged for this issue
on Aug 17, 2017
added a commit that references this issue on Aug 18, 2017
dc85623
sandersn

sandersn commented on Aug 18, 2017

@sandersn
Member

The previous PR got merged by mistake and is now reverted; #17912 is the PR with the fix now.

added this to the TypeScript 2.7.1 milestone on Jan 10, 2018
locked and limited conversation to collaborators on Jul 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

    Participants

    @sandersn@DanielRosenwasser@mhegazy

    Issue actions

      Unable to add numeric types that are not simply 'number' · Issue #17069 · microsoft/TypeScript