Skip to content

Boolean arithmetic #27501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
doerwalter opened this issue Oct 2, 2018 · 2 comments
Closed

Boolean arithmetic #27501

doerwalter opened this issue Oct 2, 2018 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@doerwalter
Copy link

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);
                    ~~~~~~~
@ghost
Copy link

ghost commented Oct 2, 2018

See https://stackoverflow.com/questions/29918324/is-typescript-really-a-superset-of-javascript

The whole purpose of TypeScript is to complain about code that looks fishy, such as relying on implicit conversions. It's easy to change this to an explicit conversion using return Number(a > b) - Number(a < b);.

@ghost ghost added the Working as Intended The behavior described is the intended behavior; this is not a bug label Oct 2, 2018
@RyanCavanaugh
Copy link
Member

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants