打字稿检查对象是否可迭代

时间:2020-03-12 15:17:41

标签: typescript

我有一个想要在其中将一个或多个对象添加到私有集合的方法的类。我要这样做的方法是使用重载和实现,以便调用者可以使用与添加对象相同的方法来添加一个对象。我目前有这样的工作方式:

import { InterfaceType } from "some/data-model/directory";

export class MyClass {
    private _collection: Array<InterfaceType>;

    constructor() {
        this._collection = [];
    }

    /**
     * Adds a new InterfaceType to the stored InterfaceTypes.
     * @param it The new InterfaceType to be stored.
     */
    public push(it: InterfaceType): void;

    /**
     * Adds new InterfaceTypes to the stored InterfaceTypes.
     * @param its The collection of new InterfaceTypes to be stored.
     */
    public push(its: Iterable<InterfaceType>): void;

    public push(i: InterfaceType | Iterable<InterfaceType>): void {
        if (typeof(i[Symbol.iterator]) === "function") {
            this._collection = this._collection.concat(Array.from(i as Iterable<InterfaceType>));
            return;
        }
        this._collection.push(i as InterfaceType);
    }

但是请注意as语句。当我将其键入为InterfaceType | Array<InterfaceType>时,我不需要添加它们,因为Typescript在我检查i instanceof Array时就可以识别,但是因为Iterable是一个接口,所以我无法直接检查{{ 1}}。

所以我的问题是:如何使Typescript识别出我已经检查并处理了参数为instanceof而不使用Iterable的情况?没办法吗?

0 个答案:

没有答案