0

Except for memory save, there is any functional reason to use undefined TypeScript?

null is more convenient in most situations. For example, when using JSON, only null is accepted.

If I need to return something "undefined" in a function, in TypeScript I could return { a: 123 } instead of { a: 123, b: undefined }

Can I stop using undefined? Or there are other reasons to use undefined instead of null in TypeScript?

I am talking about an independent strongly typed TS project (without plain Javascript dependencies). I.e. with "strict": true.

Edit: The question has been marked as duplicated. But the linked question is about Javascript and doesn't respond to my problem. My question is about Typescript only, where the use of undefined is not always required thanks to the Typescript abstractions.

miqrc
  • 1,964
  • 2
  • 18
  • 24
  • The same reasons that you have in Javascript. you will find lot of links explaining the differences between them.just one example: typeof null === 'object' while typeof undefined === 'undefined'. – quirimmo Jan 03 '19 at 09:15
  • You don't usually explicitly assign `undefined`. But you expect and check it a lot. – Denys Séguret Jan 03 '19 at 09:16
  • I've had many situations where I needed to check if something returned an object or just nothing. In such cases checking for an object wouldn't help as (as mentioned before), `null` would return `object`. – icecub Jan 03 '19 at 09:17
  • Thanks for your answers. I understand your points but in a strongly typed TS project, where you explicitly define the return types I won't need to use `undefined`. Instead, if If I try to pass an `undefined` object, I will get a **compilation** error: `undefined.ts(12,6): error TS2345: Argument of type 'undefined' is not assignable to parameter of type 'MyClass'`. – miqrc Jan 03 '19 at 10:01

0 Answers0