简体   繁体   English

如何在 typescript 中键入定长生成器?

[英]How to type a fixed-length generator in typescript?

I have a Vector2 class in typescript below.我在下面的 typescript 中有一个 Vector2 class。

// 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, unkown> {
    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();

This code works perfectly fine according to my design.根据我的设计,这段代码工作得很好。 However typescript doesn't seem to know how many arguments are supplied and keeps warning me about it;但是typescript似乎不知道提供了多少 arguments 并一直警告我; unless I directly cast it to a tuple of 2 numbers like this:除非我直接将其转换为 2 个数字的元组,如下所示:

ctx.moveTo(...(a as unknown as [number, number]))

Questions:问题:

  1. Is there a way to tell typescript that my Vector2 instances will be deconstructed into a fixed-length tuple when I use the spread operator?有没有办法告诉typescript当我使用扩展运算符时,我的 Vector2 实例将被解构为一个固定长度的元组?
  2. Is there a way to type a generator with a fixed length?有没有办法输入一个固定长度的生成器?

I don't know if a generator function is the correct abstraction here.我不知道生成器 function 是否是正确的抽象。 Usually you'd use one where the length of items you're yielding is variable or unknown.通常你会使用一个你产生的项目的长度是可变的或未知的。

Why not work with an implementation like this:为什么不使用这样的实现:

class Vector2 {
  public toArray(): [number, number] {
    return [this.x, this.x];
  }
}

ctx.moveTo(...myVector.toArray());

This way the TypeScript compiler knows the type returned by toArray , and knows it will be valid when applied to ctx.moveTo这样 TypeScript 编译器就知道toArray返回的类型,并且知道它在应用于ctx.moveTo时是有效的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM