In Functional languages, I can define a method where the signature clearly says that either the method returns Type A or Type B. ex:
class AppError(message: String)
public convertToString(input: Int) : Either[AppError, String]
The left side is always the un-happy path, and right side is the happy path. I am trying to do something similar in typescript. I wrote this code
type AppError = {message: String, errorCode: number}
function doSomething(param1: number) : AppError | string {
if (param1 < 0) {
return {"message": "param1 cannot be less than 0"}
} else {
return +param1
}
}
const result3 = doSomething(-1)
if (typeof result3 === "AppError") {
console.log("got this exception" + result3.message)
} else
console.log("got result " + result3)
}
But the typescript compiler says
This condition will always return 'false' since the types '"string" | "number" | "bigint" |
"boolean" | "symbol" | "undefined" | "object" | "function"' and '"AppError"' have no
overlap.ts(2367)
I googled and I found this thread but I still don't understand why will typeof x always be false? My code is returning the AppError object if you pass a negative number and in that case, the typeof result3 === 'AppError' should evaluate to true.