0

I'm used to working in functional languages with monadic constructs such as Option or Optional. I'm aware of libraries like fp-ts which offer these constructs in TS/JS. However I'm interested to know how imperative developers represent optional values in typescript.

From what I can see null or undefined can both be used along with a guard e.g.

const user = getUser(id)

if (maybeUser) { 
  // do something
} else {
 // do something else
}

given this scenarios what is the correct return type for getUser? User | null or User | undefined. To me, null seems more explicit, yet undefined seems more common. I think I'm correct in saying that name?: string is a shortcut for name: string | undefined

Toby
  • 1

1 Answers1

0

when we do not assign any value to a variable, the JavaScript engine treats it as undefined. The null value is assigned by the programmer to indicate that the variable has nothing inside of it, but intends to have a value later in the program execution.

In the following link, you can find an answer to your question: https://howtodoinjava.com/typescript/undefined-vs-null/

Also in the case of the elvis operator that you posted:

const hey = (hey?:string) => {
  console.log(typeof hey)
}

will be translated as:

declare const hey: (hey?: string | undefined) => void;
botana_dev
  • 418
  • 4
  • 16