Skip to content

Improve error reporting: Missing "else" branch for if expression #1104

@isaacabraham

Description

@isaacabraham

What

Developers coming from other statement based languages often fall foul of the following: -

let x = 10
let y =
   if x > 10 then "test"

As if is an expression in F#, you need to provide an "else" branch as well. The error message is not helpful: -

error FS0001: This expression was expected to have type
    unit    
but here has type
    string   

Why

Developers coming from other languages are used to working with statements, not expressions, where it is legal to only have a single branch of code in a conditional. It's not obvious from the current error message what the issue is; in fact the solution suggests that you should ignore the result of the branch in order that it gives unit back!

How

A better error message might be something like: -

You have not supplied the "else" case for this if expression. If / then is an expression and so must always return some result in all cases"

This should also apply to if / elif / elif with a missing "else".

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions