Skip to content

Union not narrowed with typeof x.y as a discriminant #32399

Open
@tusklozeleniy

Description

@tusklozeleniy

TypeScript Version: 3.6.0-dev.20190713

Search Terms: TS2339, union type object, union type property does not exist
And github suggestions while I was writing the title.

Code

type Test = {
    someKey: false
} | {
    someKey: {
        someKeyInside?: number
    },
    someKeyThatExistOnlyIfOtherKeyIsNotFalse: string;
};

declare const test: Test;

if (typeof test.someKey === 'object') {
    console.log(test.someKeyThatExistOnlyIfOtherKeyIsNotFalse);
}

Expected behavior:
String in someKeyThatExistOnlyIfOtherKeyIsNotFalse should be logged

Actual behavior:

error TS2339: Property 'someKeyThatExistOnlyIfSomeKeyIsNotFalse' does not exist on type 'Test2'.
  Property 'someKeyThatExistOnlyIfSomeKeyIsNotFalse' does not exist on type '{ someKey: false; }'.

29     console.log(test2.someKeyThatExistOnlyIfSomeKeyIsNotFalse); // TS2339: Property 'someKeyThatExistOnlyIfSomeKeyIsNotFalse' does not exist on type '{ someKey: false; }'.

Playground Link:
https://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAKhDOwCMUC8UDeAoKurwHsBbCAaQhAC4oAzAQwBt4IsBfKAH0xz0JPKrc8w-MTIUAkgDt4ASwAmEalICuRAEYQATj1ysANLtH8KMABZ1gAUQAesxAHkpDEBJoPgZ7QInwAcgTAAGKMzNSIWrJSAOYA3GzxWIoAxgx0WtDJBDLAUMAIyNRwiEiJsjRQABT5JQB0fOIgAJRCeFkyBAwQtQwE0dUFSPViAuaWtvbATi5uHl5aPv6BIUwQTbFQAPSbUA6kAIRsWFigkLAFAExorbgNAtT0q2ycN8aN1NgieNuwXlDZLn+Umg8nKNG0ECkyWgNC0xDy4GgxWQ+jePhkCkydCkUE0UBUUkUNCiEHkQLRFCMwjukgxigA-Mo1JodMIDEYaSAxtY7I5nK53J5vJIlsFQkp8MBIjF4qxEik0hkoO1EHlLkVLmUKtVEQQKjVgBdhiYQGhUOgAOQEdQAKwgyWAFpanza2UIXR6fQGiCNnO5Ez5M0F80WATFq3WWx2MAAyhcAMzxgCc1AACnDIFpQFALX6LDzJtMBXNha5RStmBaoPICAgoFJAlAILzctkEWcLRgKYJHswNqwLbU2EA

Take a look at type Test1. The only one difference from type Test2 is someKeyInside should be always defined.

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptEffort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions