Skip to content

Add Length Parameter to typed arrays #18471

Open
@HyphnKnight

Description

@HyphnKnight

The goal is pretty straight forward, since typed arrays have a fixed length it would be a more accurate and helpful type it you could specify length. Then you could get complaints if you try to assign or access a higher index or use a array of the incorrect length.

Code

type Vector2d = Int32Array<2>;
type Vector3d = Int32Array<3>;
type Matrix = Int32Array<16>;

const add =
  (vecA:Vector2d) =>
    (vecB:Vector2d, target:Vector2d = new Int32Array(2) ):Vector2d => {
      target[0] = vecA[0] + vecB[0];
      target[1] = vecA[1] + vecB[1];
      return target;
    };

const add3d =
  (vecA:Vector3d) =>
    (vecB:Vector3d, target:Vector3d = new Int32Array(3) ):Vector3d => {
      target[0] = vecA[0] + vecB[0];
      target[1] = vecA[1] + vecB[1];
      target[2] = vecA[2] + vecB[2];
      return target;
    };

const position = new Int32Array(2);
const position3d = new Int32Array(3);
const velocity = new Int32Array([1,1]);
const velocity3d = new Int32Array([1,2,3]);

add(position)(velocity, position);
const newPosition = add(position)(velocity);

add3d(position3d)(velocity3d, position3d);
add(position3d)(velocity3d, position3d); // Fails due to incorrect array length

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions