Coming from a background of working with functional languages that utilize monadic constructs like Option or Optional, I have noticed libraries such as fp-ts that provide these features in TypeScript/JavaScript. However, I am curious to understand how developers who prefer imperative programming represent optional values in TypeScript.
Based on my observation, both null and undefined can be used along with a guard like the example below:
const user = getUser(id)
if (maybeUser) {
// do something
} else {
// do something else
}
In this context, what would be the appropriate return type for the getUser function? Is it User | null
or User | undefined
? Personally, I find null to be more explicit, but undefined seems to be more commonly used. Additionally, I believe that name?: string
is essentially a shorthand for name: string | undefined
.