Skip to content

Provide a way to type a fix-length tuple-like generator/iterator #42033

Open
@zojize

Description

@zojize

Search Terms

  • generator
  • iterator

Suggestion

Express a fixed-length generator.

Use Cases

  • Allows the spread syntax on functions to know how many arguments is deconstructed (see examples below)

Examples

stackoverflow question

// Vector2.ts
class Vector2 {
  constructor (public x, public y) {
    this.x = x;
    this.y = y;
  }

  //... A bunch of vector methods

  public* [Symbol.iterator]: Generator<number, void, unknown> {
    yield this.x;
    yield this.y;
  }
}

// main.js
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');

const a = new Vector2(0, 0);
const b = new Vector2(10, 10);

ctx.beginPath();
ctx.moveTo(...a);
// works correctly, but with this warning: 
// Expected 2 arguments, but got 0 or more.ts(2556)
ctx.lineTo(...b);
ctx.stroke();
ctx.closePath();

Right now, the code above produces the correct behavior. However, typescript doesn't not recognize how many arguments is passed to ctx.moveTo and ctx.lineTo therefore it warns me about it.

My Implementation

There could be an tuple-like syntax for generators as well, for example:

public* [Symbol.iterator]: *[number, number] {
    yield this.x;
    yield this.y;
  }

With this syntax, typescript recognizes how many argument is deconstructed by the spread operator, and knows its a generator with the prepending *.

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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 featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions