Skip to content

Class member variable types incorrectly narrowed for constant assignments when calling member functions afterwardsΒ #62148

@mikonse

Description

@mikonse

πŸ”Ž Search Terms

invalid constant type narrowing

πŸ•— Version & Regression Information

Bug is visible on 5.9.1-rc1 as well as 4.9.5 (tested on typescript playground)

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.0-dev.20250730#code/MYGwhgzhAEBiD28BGYBO0DeAoavoAdUBLANzABcBTaAEwrAC5olERKwA7aAXmgDMwICJQDcWHHkKkK1PgFcOwABQBKTBLx5yACyIQAdHXJge-QcLGbNOvfvg7KqALKUAtkkewFylZau4bAyMwEWgAejDoPVpKGjlgWOhIaGB4DghjDnJocgBPfGoAAwEhSkKoxXhUVEpgchBcjWgAX3FNKTIqaHttRxd3T29oVXV-AN0g+lNyVDlRJtbmoA

πŸ’» Code

class Foobar {
    private data: boolean = false;

    private func() {
        this.data = false;
        this.otherMemberFunc();
        // is deduced as constant type `false` incorrectly even though the control flow flow can obviously mutate the variable
        this.data;
    }

    private otherMemberFunc () {
        this.data = true;
    }
}

πŸ™ Actual behavior

Typescript deduces the member type as constant even though a later member function call in the class can very easily mutate the data member and therefore invalidate the constant type narrowing.

πŸ™‚ Expected behavior

Typescript should discard any type narrowing on class data members when calling member functions after the type narrowing.

I.e. in the posted code example this.data should again be deduced as a boolean instead of constant false after calling the member function since the member function might definitely mutate any data accessible through this in a class and therefore invalidate any type narrowing on member variables done before.

This might be a complex problem overall since this will extend to nested objects and arrays which are accessed through this in a class member;

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions