Why doesn't rust narrow enums after an "if let\

35 points GeeWengel

I've been wondering about something lately. Take this code:

fn main() -> Result<(), String> {
    let my_var: Result<String, String> = Ok("some_string".to_string());
    
    if let Err(err) = my_var {
        return Err("Oh not".to_string()) // Return something in this block - we now know that the enum cannot be an Err variant below this block
    }
    
    //  We _know_ that my_var is a Ok(String) here - but I still have to call unwrap on it
    my_var.chars(); // This is not valid
    
    Ok(())
}

Is there a reason that the Rust compiler doesn't automatically narrow the type here - like a language like TypeScript might do. Is this something that's been considered and rejected?