You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I made the some library that is meant to be used for nullable values.
Unfortunately JS has two values that signify a missing value, null and undefined.
For example, array indexing returns undefined on invalid index, but Array.find returns null if no match is found.
TS type system separates these values into two different types, and you can't use null as a value for optional values. This means that making the some-package functions return T|null|undefined is not viable, since in most cases only one of the types is valid.
I first considered creating 3 packages for handling missing values (undefined, null and undefined|null, but that seems bad in many ways.
Another option would be to decide on an "official" missing value type and make all functions return that. The functions would accept both as arguments, but would always return T|undefined or T|null.
If you need the other one, you can use the JS foo() || null pattern.
A third option might be to make the return value generic, but constrained to T extends undefined|null, and provide an optional parameter that is used to assign the missing value case return value:
const map = <A, B, N extends null | undefined = undefined>(value: A|null|undefined, fn: (a: A) => B, missingCase?: N): B|N => value == null ? missingCase : fn(value)
map(value, n => n) // returns T|undefined
map(value, n => n, null) // returns T|null
The text was updated successfully, but these errors were encountered:
I made the
some
library that is meant to be used for nullable values.Unfortunately JS has two values that signify a missing value,
null
andundefined
.For example, array indexing returns
undefined
on invalid index, but Array.find returnsnull
if no match is found.TS type system separates these values into two different types, and you can't use
null
as a value for optional values. This means that making thesome
-package functions returnT|null|undefined
is not viable, since in most cases only one of the types is valid.I first considered creating 3 packages for handling missing values (
undefined
,null
andundefined|null
, but that seems bad in many ways.Another option would be to decide on an "official" missing value type and make all functions return that. The functions would accept both as arguments, but would always return
T|undefined
orT|null
.If you need the other one, you can use the JS
foo() || null
pattern.A third option might be to make the return value generic, but constrained to
T extends undefined|null
, and provide an optional parameter that is used to assign the missing value case return value:The text was updated successfully, but these errors were encountered: