Skip to content

cached typeof does not narrow down types of a union #41627

Closed
@AndyOGo

Description

@AndyOGo

TypeScript Version: v4.0.5

Search Terms: typeof, cached typeof

Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
interface TestHash {
    [index: string]: boolean;
}
type TestType = boolean | TestHash;

function testTypeOf(value: TestType) {
    const valueType = typeof value;

    if (valueType === "boolean") {
        return value;
    }

    if (valueType === "object") {
        return Object.keys(value).every((key) => value[key]);
    }

    return !!value
}

Expected behavior:
The cached result of typeof should also be used to narrow down the union type.

Actual behavior:

It errors with:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'TestType'. No index signature with a parameter of type 'string' was found on type 'TestType'.

Playground Link:

Broken: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgCoQM5gBJwwC2QG8AoZc5AbVABMIAPALmSylAHMBdZgIwHs+AGwhwQAbhIBfEmACeABxTosqBSgC8yfkJEhkAHzSYcefBJIwAriARhgfPZBVqA8jAAUANziDLEZspgqooAlMRkFAgOWMjevhDBGshyinwwsT5+5hTIwOlemQlqyOqlyABE2sKi5WGkOTlQEGCWUHpxWRHk0l25+R1FiiVl5Xw8AFYQtrXhDRRNLW3ILhNTYAB0ANYQshgF8SHrEJ7Qsu7u27Jh6gB8GfGUl5whEjk9jc2tegCE3wNSJEB5CAA

Working: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgCoQM5gBJwwC2QG8AoZc5AbVABMIAPALmSylAHMBdZgIwHs+AGwhwQAbhIBfEmACeABxTosqBSgC8yfkJEhkAHzSYcefBJIwAriARhgfPZBVqA8jAAUANziDLEZspgqooAlMRkFMAwyO5yinzR3r4a6poARNrComlhpBT5yFAQYJZQekl+EvnSEeRRMXEQCcgVKel8PABWELY54QUURSVlyC5dPWAAdADWELIYXj5+IZMQntCy7u6zsmHqAHwtSxCUO5whVRQ1+UOlegCE961SJK-kQA

Related Issues:

Activity

MartinJohns

MartinJohns commented on Nov 21, 2020

@MartinJohns
Contributor

Duplicate of #12184.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @AndyOGo@MartinJohns

        Issue actions

          cached typeof does not narrow down types of a union · Issue #41627 · microsoft/TypeScript