TypeScript 4.4: Control Flow Analysis for Aliased Conditions

TypeScript 4.4 makes the compiler much smarter about variable checks. Previously, if you extracted a condition into a variable, TS lost the type narrowing.

function foo(arg: string | unknown) {
    const isString = typeof arg === "string";
    
    // In TS 4.3: Error, 'arg' is unknown
    // In TS 4.4: OK! Compiler knows 'isString' implies arg is string
    if (isString) {
        console.log(arg.toUpperCase());
    }
}

This allows for much cleaner guard clauses without forcing you to repeat the specific check logic inline.


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.