Skip to content

Type guard not work in union type of objects #30506

Closed
@zheeeng

Description

@zheeeng

TypeScript Version: 3.3.3.3333

Search Terms:
type guard, union type of objects, typeof

Code

function fn(i: { foo: string, bar: number, baz: boolean } | { foo: number, bar: boolean }) {
    // Notice: i.foo has two different types in intelligence and after written down.
    if (typeof i.foo === 'string') {
       // as screenshot, in intelligence, 'i.foo' is of type 'string | number' 
        i.foo // after written down, i.foo becomes 'string'
        i.bar // always 'number | boolean'
    }
}

Code 2

function fn(i: { foo: string, bar: number, baz: boolean } | { foo: number, bar: boolean }) {
    // NOTICE: we added parenthesis
    if ((typeof i.foo) === 'string') {
        i.foo // string | number

        i.bar // number | boolean
    }
}

Expected behavior:

in 'if' branch, ‘i’ should be { foo: string, bar: number, baz: boolean }

Actual behavior:

As comments says.

image

Playground Link:
http://www.typescriptlang.org/play/index.html#src=function%20fn(i%3A%20%7B%20foo%3A%20string%2C%20bar%3A%20number%2C%20baz%3A%20boolean%20%7D%20%7C%20%7B%20foo%3A%20number%2C%20bar%3A%20boolean%20%7D)%20%7B%0D%0A%20%20%20%20if%20(typeof%20i.foo%20%3D%3D%3D%20'string')%20%7B%0D%0A%20%20%20%20%20%20%20%20i.foo%20%2F%2F%20string%20%7C%20number%0D%0A%20%20%20%20%20%20%20%20i.bar%20%2F%2F%20number%20%7C%20boolean%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions