Edgoro
Compile error · Types and qualifiers

Pine Script: return type of if/switch blocks not compatible

When an if or switch returns a value, every branch must return the same type. How to fix the Pine Script "Return type of one of the if or switch blocks" error.

Pine Editor console · line 3
Return type of one of the "if" or "switch" blocks is not compatible with return type of other block(s) (literal string; literal int)

Cause

An if or switch assigned to a variable returns the value of the last line of each branch. Here one branch returns a string and the other an int, so the result has no single type.

Broken code

TradingView reports the error on line 3.

Pine Script v6
//@version=6
indicator("Trend label", overlay = true)
trend = if close > ta.sma(close, 50)
    "Uptrend"
else
    0
if barstate.islast
    label.new(bar_index, high, trend)

Fixed code

The same script, corrected for Pine Script v6. Paste it into the Pine Editor and save.

Pine Script v6
//@version=6
indicator("Trend label", overlay = true)
trend = if close > ta.sma(close, 50)
    "Uptrend"
else
    "Downtrend"
if barstate.islast
    label.new(bar_index, high, trend)

Why it works

The variable trend takes its type from the branches. When every branch returns a string, trend is a string and can be passed to label.new(). A branch can also return na when the other branches already set the type, which is how you say "no value" for a float or a string (not for a bool in v6).

Reading the end of the message

The part in brackets lists the types the compiler found in each branch, in order: (literal string; literal int) means the first branch returns a string and the second an int. With a switch, check every case including the default => branch.

Questions

How does an if statement return a value in Pine Script?

When you assign an if or switch to a variable, the value of the last expression in the branch that runs becomes the result. If no branch runs and there is no else, the result is na (false for a bool in v6).

What does "(literal string; literal int)" at the end of the message mean?

It lists the types the compiler found in the branches, in order. Make them match, for example by returning a string in every branch.

The scripts on this page are minimal examples written to show the error and its fix, not trading systems. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Still getting an error?

Paste your script and the message into the free Pine Script error fixer: it explains what went wrong and returns a corrected v6 version. Or describe the indicator in plain English and let Edgoro write the code.