Skip to content

Incorrect type inference when using object index #17011

Closed
@zlepper

Description

@zlepper

TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
2.4.1

Code

function test(paramsObject: { [key: string]: string | Array<string> }) {
    for (let key in paramsObject) {
        if (paramsObject.hasOwnProperty(key)) {
            if (Array.isArray(paramsObject[key])) {
                doArray(paramsObject[key]);
            } else {
                doString(paramsObject[key]);
            }
        }
    }
}


function doString(s: string) {
    console.log(s);
}

function doArray<T>(a: Array<T>) {
    console.log(a);
}

Expected behavior:
Typescript should be able to infer that paramsObject[key] is still a string or string array after Array.isArray has been called. It can't change.
It works correct if I assign paramsObject[key] to a variable beforehand, and then use that variable in both the check and the doArray and doString.

Actual behavior:
Argument of type 'string | string[]' is not assignable to parameter of type 'string[]' for doArray
and
Argument of type 'string | string[]' is not assignable to parameter of type 'string'. for doString

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions