Skip to content

Boolean arithmetic #27501

Closed
Closed
@doerwalter

Description

@doerwalter

TypeScript Version: 3.0.3

Search Terms: bool arithmetic

Code

function cmp(a : string, b : string) : number
{
	return (a > b) - (a < b);
}

Expected behavior:

I would have expected that Typescript compiles this source without any complaints, as Javascript treats boolean values true and false as the numbers 1 and 0 in arithmetic expressions, but it seems that Typescript doesn't.

In fact the Javascript version of this function does work as expected:

function cmp(a, b)
{
	return (a > b) - (a < b);
}

cmp("foo", "bar") returns 1 and cmp("bar", "foo") returns -1.

Actual behavior:

Typescript complains with the following error messages:

src/boolarithmetic.ts:3:9 - error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

3  return (a > b) - (a < b);
          ~~~~~~~

src/boolarithmetic.ts:3:19 - error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

3  return (a > b) - (a < b);
                    ~~~~~~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions