英文:
Typing the generator "chain" function
问题
我有以下函数:
function* chain(...iters) {
for (let it of iters)
yield* it
}
它接受一系列可迭代对象,并创建一个生成器,按顺序从每个对象中生成值。
我不确定如何正确地为支持混合类型的可迭代对象进行类型定义。如果我的输入是像 Iterable<X>
、Iterable<Y>
等,那么结果应该是 Iterable<X | Y>
。如何为可变参数编写这个类型定义?
英文:
I've got the following function:
function* chain(...iters) {
for (let it of iters)
yield* it
}
It accepts a list of iterables and creates a generator that yields sequentially from each one.
I'm not sure how to type it correctly to support mixed-type iterables. If my inputs are like Iterable<X>
, Iterable<Y>
etc then the result should be Iterable<X | Y>
. How to write this for a variadic argument?
答案1
得分: 4
以下是翻译好的部分:
See this GitHub issue for more info:
microsoft/TypeScript#41646 - 允许泛型yield*
类型
通过使用受限制的泛型类型参数,生成器函数的返回类型可以从其参数中派生出来。
type Chain = <Iters extends readonly Iterable<unknown>[]>(
...iters: Iters
) => Iters[number];
在上面的函数签名中,泛型 Iters
必须能够分配给一个类型,该类型是不可变的 Iterable<unknown>
元素数组。因此,剩余参数 iters
中的每个参数都必须能够分配给 Iterable<unknown>
。这将允许编译器推断每个可迭代参数的生成类型。
以下是将其应用于您展示的实现的示例,然后使用您的播放链接中的一些示例函数,以查看推断的返回类型:
declare function test1(): Iterable<number>;
declare function test2(): Iterable<string>;
const chain: Chain = function* (...iters) {
for (let it of iters) yield* it;
};
const iter = chain(test1(), test2());
//^? const iter: Iterable<number> | Iterable<string>;
for (const value of iter) {}
//^? const value: string | number
您可以看到,推断的返回类型是 Iterable<number> | Iterable<string>
,并且在 for...of
循环中使用它会产生一个生成类型,该生成类型是联合了联合中每个可迭代对象的生成类型。
我认为这已经根据您的问题标准产生了令人满意的结果,但实际的返回类型仍然可以改进以更准确地表示返回的可迭代对象本身。
通过使用一种类型工具(改编自链接的 GitHub 问题中的内容),可以从可迭代类型内部提取生成类型:
type YieldedFromIterable<
I extends
| Iterable<unknown>
| Iterator<unknown>
| IterableIterator<unknown>
| Generator<unknown>
> = I extends
| Iterable<infer T>
| Iterator<infer T>
| IterableIterator<infer T>
| Generator<infer T>
? T
: never;
...可以为函数创建一种替代返回类型:
type Chain = <Iters extends readonly Iterable<unknown>[]>(
...iters: Iters
) => Iterable<YieldedFromIterable<Iters[number]>>;
与第一个函数签名的返回类型相比(该返回类型是联合了每个可迭代参数的生成类型),这个返回类型是一个单一的可迭代对象,它生成了从每个参数派生的联合值 - 并且在使用它时看起来像这样:
const chain: Chain = function* (...iters) {
for (let it of iters) yield* it as any;
};
const iter = chain(test1(), test2());
//^? const iter: Iterable<string | number>;
for (const value of iter) {}
//^? const value: string | number
结束语:
在第二个示例中,不对第二个示例的生成值使用类型断言会导致编译器错误:
<details>
<summary>英文:</summary>
> See this GitHub issue for more info:
> [microsoft/TypeScript#41646 - Allow generic `yield*` types](https://github.com/microsoft/TypeScript/issues/41646)
By using a [constrained generic type parameter](https://www.typescriptlang.org/docs/handbook/2/generics.html#using-type-parameters-in-generic-constraints), the return type of your generator function can be derived from its arguments.
```lang-ts
type Chain = <Iters extends readonly Iterable<unknown>[]>(
...iters: Iters
) => Iters[number];
In the function signature above, the generic Iters
must be assignable to a type that is a readonly array of Iterable<unknown>
elements. So, each argument in the rest parameter iters
must be assignable to Iterable<unknown>
. This will allow the compiler to infer the yielded type of each iterable argument.
Here's an example of applying it to the implementation that you showed, and then using it with a couple of example functions from your playground link in order to see the inferred return type:
declare function test1(): Iterable<number>;
declare function test2(): Iterable<string>;
const chain: Chain = function* (...iters) {
for (let it of iters) yield* it;
};
const iter = chain(test1(), test2());
//^? const iter: Iterable<number> | Iterable<string>
for (const value of iter) {}
//^? const value: string | number
You can see that the inferred return type is Iterable<number> | Iterable<string>
, and that using it in a for...of
loop produces a yielded value that is the union of the yield type of each iterable in the union.
I think this already produces a satisfactory result according to your question criteria, but the actual return type can still be improved to more accurately represent the returned iterable itself.
By using a type utility (adapted from content in the linked GitHub issue) which extracts the yielded type from within an iterable type:
type YieldedFromIterable<
I extends
| Iterable<unknown>
| Iterator<unknown>
| IterableIterator<unknown>
| Generator<unknown>
> = I extends
| Iterable<infer T>
| Iterator<infer T>
| IterableIterator<infer T>
| Generator<infer T>
? T
: never;
...an alternative return type can be created for the function:
type Chain = <Iters extends readonly Iterable<unknown>[]>(
...iters: Iters
) => Iterable<YieldedFromIterable<Iters[number]>>;
In juxtaposition with the first function signature's return type (which was a union of each of the iterable arguments), this one is a single iterable which yields a union value derived from each argument — and using it looks like this:
const chain: Chain = function* (...iters) {
for (let it of iters) yield* it as any;
};
const iter = chain(test1(), test2());
//^? const iter: Iterable<string | number>
for (const value of iter) {}
//^? const value: string | number
Concluding thoughts:
Not using a type assertion on the yielded value of the second example causes a compiler error:
const chain: Chain = function* (...iters) { /*
~~~~~
Type '<Iters extends readonly Iterable<unknown>[]>(...iters: Iters) => Generator<unknown, void, undefined>' is not assignable to type 'Chain'.
Call signature return types 'Generator<unknown, void, undefined>' and 'Iterable<YieldedFromIterable<Iters[number]>>' are incompatible.
The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types.
Type 'IteratorResult<unknown, void>' is not assignable to type 'IteratorResult<YieldedFromIterable<Iters[number]>, any>'.
Type 'IteratorYieldResult<unknown>' is not assignable to type 'IteratorResult<YieldedFromIterable<Iters[number]>, any>'.
Type 'IteratorYieldResult<unknown>' is not assignable to type 'IteratorYieldResult<YieldedFromIterable<Iters[number]>>'.
Type 'unknown' is not assignable to type 'YieldedFromIterable<Iters[number]>'.(2322) */
for (let it of iters) yield* it;
};
I think this is caused by a limitation of TypeScript's control flow analysis (but perhaps I'm wrong about that and someone else can provide more clarity).
A solution is to assert the value's type, like this:
const chain: Chain = function* (...iters) {
for (let it of iters) yield* it as Iterable<YieldedFromIterable<typeof iters[number]>>; // ok
};
// OR
const chain: Chain = function* (...iters) {
for (let it of iters) yield* it as any; // ok
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论