Skip to content

Number subtypes: Integer. Long, Foat, Double #2077

Open
@stokito

Description

@stokito

JS doesn't have a distinct int/Integer/int32 type but it would be really helpful and can prevent from many errors. Same for float/double/float32. In the same time JS has Int8Array/Uint8Array which is kind of imply existing of Int8/UInt8 but not directly declared.
I understand that the JsDoc here follows JS/EcmaScript/TypeScript spec but maybe it's possible to declare some number's "aliases" for int/float that will be fine syntactically.
In real life code base I saw a lot of @type {int} usages. This is due to IntelliJ IDE is fine with it and just threat it as a number. E.g. you can assign float numbers to an int field. I reported the problem.
The Idea is also fine with integer as a real type.

Here I tested a small sample of code:

class Integer extends Number {
}

class UInteger extends Number {
}

/**
 * @typedef {number} Int8
 * @typedef {number} Int16
 * @typedef {number} Int32
 * @typedef {number} Int64
 * @typedef {number} UInt8
 * @typedef {number} UInt16
 * @typedef {number} UInt32
 * @typedef {number} UInt64
 * @typedef {Int32} Int
 */

class I {
  /** @type {Integer} */
  IdInteger
  /** @type {UInteger} */
  IdUInteger
  /** @type {Int} */
  IdInt
  /** @type {Int32} */
  Id16
  /** @type {int} */
  IdI
}

var s = new I()
s.IdInteger = 0 // OK. IntelliJ is totally fine with this assignment if the
s.IdInteger = null // OK
s.IdUInteger = 0 // IntelliJ Warning: Assigned expression type number is not assignable to type UInteger
s.IdInt = 0 // OK
s.Id16 = 0 // OK
s.Id16 = 0.5 // should be an error: float not allowed
s.UId16 = -0.5 // should be an error: negative number
s.IdI = 0
s.IdI = '0' // IntelliJ Warning: Assigned expression type string is not assignable to type int

s.IdInteger = new Integer(42) // IntelliJ Warning: Method expression is not of Function type

If the both IntelliJ and JsDoc can add the layer of type check that may help to find many errors.

Similarly all kinds of int8/byte, int16/small, int64/long would be just great.

Related:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions