Typescript:将IterableIterator扩展为数组类型,但返回一个简单类型 [英] Typescript: extending IterableIterator for array type but return a simple type

查看:308
本文介绍了Typescript:将IterableIterator扩展为数组类型,但返回一个简单类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用类似于 Array.flat()的方法来扩展 IterableIterator .编写方法本身没问题,扩展 IterableIterator 的接口也很容易.因此,javascript部分处于控制之中.不幸的是,我无法让打字稿编译器了解我想要的内容.

I am trying to extend the IterableIterator with a method similar to Array.flat(). Writing the method itself is no problem, extending the interface for IterableIterator is also easy. So the javascript part is under control. Unfortunately I can't get the typescript compiler to understand what I want.

我应该如何在IterableIterator中声明Flatten,以使打字稿将其理解为 number 而不是像现在这样的 number [] ?

How should I declare Flatten in IterableIterator for item to be understood by typescript as a number and not as a number[] like it is now?

注意:如果我用 if(item instanceof number){} 包装 total + = item ,则该方法有效.只是为了完成,该方法当前看起来像这样:

NOTE: if I wrap total+=item with if(item instanceof number) {} the method works. Just for completion the method looks currently like this:

function* iterable_flatten<T>(this: Iterable<T[]>): Generator<T> {
    for (let item of this) {
        for (let itemitem of item)
            yield itemitem;
    }
}

推荐答案

阅读

After reading this article I found out that the solution is to create a type which infers the base type of the array :

type BaseTypeOfArray<T> = T extends Array<infer I> ? I : "never";

然后使用它来获取声明中的基类型:

And then use it to get the base type in the declaration:

flatten(this: Iterable<T>): Generator<BaseTypeOfArray<T>>;

这篇关于Typescript:将IterableIterator扩展为数组类型,但返回一个简单类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆