Skip to content

Issue with Array.isArray typeguard after upgrading from 4.1.2 to 4.1.3 #41984

Closed
@mwgamble

Description

@mwgamble

TypeScript Version: 4.2.0-dev.20201211

Search Terms:

re: Array.isArray

Code

interface TestCase<T extends string | number> {
    readonly val1: T | ReadonlyArray<T>;
    readonly val2: ReadonlyArray<T>;
}

interface MultiCaseFixture<T> {
    cases: T[];
}

function subDataFunc(): TestCase<string | number>[] {
    return [
        { val1: "a", val2: ["a", "b", "c"] },
        { val1: 2, val2: [1, 2, 3] },
        { val1: ["a", "z"], val2: ["x", "y", "z"] },
        { val1: [5, 10], val2: [10, 100, 1000] },
    ];
}

function dataFunc<T>(subFunc: () => T[]): MultiCaseFixture<T> {
    return { cases: subFunc() };
}

function testFunc() {
    const fixture = dataFunc<TestCase<string | number>>(subDataFunc);
    fixture.cases.forEach(({ val1, val2 }) => {
        if (Array.isArray(val1)) {
            const reversedVal1 = val1.slice().reverse();
            console.log(reversedVal1);
        } else {
            console.log(val1);
        }
        console.log(val2);
    });
}

testFunc();

Expected behavior:

This code should compile properly without issues. It compiles fine on 4.1.2 and also compiled fine on previous releases going all the way back to at least 3.8.

Actual behavior:

I get this output from tsc with the command-line yarn run tsc test.ts. There is no tsconfig.json file in the folder at the time.

test.ts:27:47 - error TS2339: Property 'reverse' does not exist on type 'string | any[]'.
  Property 'reverse' does not exist on type 'string'.

27             const reversedVal1 = val1.slice().reverse();
                                                 ~~~~~~~


Found 1 error.

Playground Link: https://www.typescriptlang.org/play?ts=4.2.0-dev.20201211#code/JYOwLgpgTgZghgYwgAgCoQM5gMJwxAHlWQgA9IQATDZLKUAc2QB9kQBXAWwCNoA+ZAG8AUMjHIoEOJQD2IADYBPZADc48gIwAuNC2QAlKbIWKAglChxFRPgG5R4ydLlLV6gEw7Dzk+cvXUO2EAX2FhUEhYRBQAWXZ5MGBcfAAxYHJ2SRshBzEEPEwdVABtAF17UOEYdhAERLladm4AETgwOBSahAAKAEoizBwCgjpGPQ4efjKc8QkIMEyQZGLc2aE3TR0AIjgtgBoNz2Wd-eQt7lOthC3S5GC91dnBDe1kdwO1eSPijQP35AAzLd7o9xM9Pq9iicDlsAF43D4eHRQ0iXRSXeHAh5rMEvZEAVgOGgADKVEV9kSSicTidSaVjVuUQmFqrV6ktKG0Ol0bN0ME1OrUdH1kABeAQlUr9ZBxBJJAppDJZQIzRzzRbrfL4DA6fncQU9Xp3Cosrrs5CQLAGkUiWYIORYZAwdILSRi5Cc9oGoiDZKEUYgJisCa8KB8Ph8pqtL1dXr2WbOpUQAB0WswyZgMigAFFEAALbrdcHqX6HO5G8WqnHAGDIbp+KzJ4AYBuKboQ3pG204tb2kCOyQqaD4SgANRL7ohyYw8mASD6ycHw4gfXjPbtDpk8hT8hkDG6S6gI-HmjjoLEwRI8nwVfXyD7GC3O737ZLZ-XoXXD6fyd3+8+7jvuIwRnpUlpgNacZAA

Related Issues:

According to #40463 and #41808, an issue with Array.isArray has already been fixed and is supposedly in 4.1.3.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptHas ReproThis issue has compiler-backed repros: https://aka.ms/ts-repros

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions