如何告诉TypeScript我的对象的类型?

时间:2017-06-16 22:43:00

标签: typescript

让我们从一些代码开始:

export function toArrayStrict(obj: Iterable<any>): any[] {
    if(obj) {
        if(isArray(obj)) {
            return obj; // error TS2322: Type 'Iterable<any>' is not assignable to type 'any[]'.

        }
        if(isFunction(obj[Symbol.iterator])) {
            return [...obj];
        }
    }
    throw new Error(`Cannot convert ${getType(obj)} to array; it is not iterable.`);
}

当我尝试编译它时会抛出错误:

  

错误TS2322:类型'Iterable'不能分配给'any []'。

我完全得到了。它不知道我已经验证obj实际上是any[]

我的问题是,如何告诉编译器isArray正在检查类型,这实际上是安全的吗?

注意,我知道如果我使用Array.isArray,错误就会消失。这个问题与此无关。我想知道我如何告诉tsc这是什么类型。

1 个答案:

答案 0 :(得分:1)

您需要使用User-Defined Type Guards

function isArray(obj: any): obj is Array<any> {
    return obj instanceof Array;
}

function isFunction(obj: any): obj is Function {
    return typeof obj === "function";
}

if (isArray(obj)) {
    return obj; // should be fine now
}