[英]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:问题:
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.