Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
AndyOGo opened this issue Nov 21, 2020 · 1 comment
Closed

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

AndyOGo opened this issue Nov 21, 2020 · 1 comment

Comments

@AndyOGo
Copy link

AndyOGo commented Nov 21, 2020

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:

@MartinJohns
Copy link
Contributor

Duplicate of #12184.

@AndyOGo AndyOGo closed this as completed Nov 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants