dotnet / dotnet/fsharp

Conditional interpolated printf formats give confusing error message

Open
#12,592 0 comments 0 reactions 0 assignees View on GitHub
Area-Diagnostics Feature Improvement Impact-Low
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 11h
Merged PRs (30d)
131

Description

**Repro steps**

```fs
let b = true
printfn (if b then $"{b}" else "")
```
https://sharplab.io/#v2:DYLgZgzgNAJiDUAfYBTALgAgEYYLwbQCcBXFAWACgAHQgSwDs0x6MAKWsbAgCxRYBIARAG8sAX0EYUwCCgyDBASiA===

**Expected behavior**

Compiles and prints `true`.

**Actual behavior**

```
error FS0001: All branches of an 'if' expression must return values implicitly convertible to the type of the first branch, which here is 'bool'. This branch returns a value of type 'unit'.
```

**Known workarounds**

```fs
let b = true
let s = ()
printfn (if b then $"{s}" else "")
```
Just kidding!
```fs
let b = true
let s : PrintfFormat<_, _, _, _> = $"{b}"
printfn (if b then s else "")
```
```fs
let b = true
printfn "%s" (if b then $"{b}" else "")
```
```fs
let b = true
printfn $"""{if b then $"{b}" else ""}""
```

**Related information**

Provide any related information (optional):

* Operating system: Windows
* .NET Runtime kind (.NET Core, .NET Framework, Mono): .NET 6
* Editing Tools (e.g. Visual Studio Version, Visual Studio): sharplab.io

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.