typescript 如何定义有序迭代器类型?

3pmvbmvn  于 2023-06-30  发布在  TypeScript
关注(0)|答案(1)|浏览(115)
interface TestIterator {
    0: boolean;
    1: any;
    2: "abc";
    length: 3;
    [Symbol.iterator]: typeof Array.prototype[Symbol.iterator];
}

// I want to build an iterator type that can be used for unpacking, which can still keep the correct type order after unpacking
const arr: TestIterator = [true, {}, "abc"]

// The following a1, a2, a3 cannot get the correct type
const [a1, a2, a3] = arr

我试图查看生成器构造的类型,我惊讶地发现生成器构造的类型也不能保持类型的顺序

function *gen()
{
    yield "abc";
    yield true;
    yield 123;
}

const view_inference_type = gen(); // The generator gets the type: const view_inference_type: Generator<true | "abc" | 123, void, unknown>

const [g1, g2, g3] = view_inference_type; // All types of g1 g2 g3 are true | "abc" | 123 .This surprises me. Normally, we expect the unpackaged types to be sequential and accurate enough

我遇到的真实的问题是,我正在使用接口的合并功能来扩展Axios的AxiosResponse接口,以便它可以解包,但我目前的方法没有获得正确的类型,因此元组方法偏离了问题。

declare module "axios"
{

    interface AxiosResponse {
        0: boolean;
        1: any;
        2: "async_try";
        length: 3;
        [Symbol.iterator]: Array[Symbol.iterator];

    }

}

有没有办法对迭代器或生成器的类型进行排序,或者手动指定类型的顺序?

webghufk

webghufk1#

对于您的场景,我认为正确的结构是tuple。查看官方文档
type TestTuple = [boolean, any,string];
https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types

相关问题