Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling null/undefined values #9

Open
katis opened this issue Nov 2, 2018 · 0 comments
Open

Handling null/undefined values #9

katis opened this issue Nov 2, 2018 · 0 comments
Labels
discussion Discussion about the library design

Comments

@katis
Copy link
Contributor

katis commented Nov 2, 2018

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
@katis katis added the discussion Discussion about the library design label Nov 2, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
discussion Discussion about the library design
Projects
None yet
Development

No branches or pull requests

1 participant