Skip to content

You actually can get Infinity type if you're clever and other fun floating point oddities #31752

Open
@rickwebiii

Description

@rickwebiii

As explained in #15135 and #15351, the Typescript team doesn't intend to support NaN and Infinity literals, due to complexity. Explicitly typing something as Infinity or -Infinity gives the error:

'Infinity' refers to a value, but is being used as a type here.

As it turns out, you actually can get the Infinity type fairly easily. Just use a really large number that parses to infinity as your type, like 1e999. -1e999 gives you negative Infinity. Fortunately, I don't believe you can get NaN from just parsing a double precision literal other than NaN itself. 0/0 is the simplest way to get NaN, but that's 2 literals and a divide.

There are a number of other floating point literal peculiarities resulting from round-off as well. I fully expect the Typescript team to "won't fix" them:

type DoesntExtend = 1.000000000000001 extends 1 ? 'yes' : 'no' // Resolves to 'no'
type Extends      = 1.0000000000000001 extends 1 ? 'yes' : 'no' // Resolves to 'yes'

Here's another.

type NegativeZero = -0 extends 0 ? 'yes' : 'no'; // Resolves to 'yes'

In this case, -0 and 0 are actually distinct numbers with different bit patterns. Both Chrome and Firefox dev consoles correctly echo -0 as -0 rather than 0. However, the IEEE-754 standard defines that 0 === -0, so I'm not surprised Typescript thinks they're the same type. The intent for this distinction is to convey the idea of limits as a numeric representation (not to mention floating point is sign-magnitude anyways, so why not embrace it). For example, 1/-Infinity and -8*0 both result in -0 rather than 0. For a type system, I'm not sure that you strictly need or want to maintain this distinction.

TypeScript Version: Repro'd on playground

Search Terms:
Infinity, NaN
Code

type Illegal = Infinity; // Doesn't compile
type Inf = 1e999; // Resolves to Infinity
type NegativeInf = -1e999; // Resolves to -Infinity

Expected behavior:

Actual behavior:

Playground Link:
Here

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DiscussionIssues which may not have code impact

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions