Just a heads up: I have enabled --strictNullChecks
Here is a function I have:
export function ensure<T, F extends T>(maybe: T | undefined, fallback: F): T {
if (isDefined<T>(maybe)) {
return maybe
}
if (fallback === undefined) {
throw new Error('Could not ensure a value; please supply a fallback for the given variable')
}
return fallback
}
I typically use this function to remove the undefined
part from a potentially undefined value.
const user = ensure(possiblyUndefinedUser, defaultUser)
My aim is for the below scenario,
const user = ensure(certainlyDefinedUser, defaultUser)
to trigger a compile time error. In other words, I want it to be against the rules to use this function with a value that the compiler already recognizes as having a value. This approach will compel me to accurately define types for my functions, as outlined below.
I've experimented with different variations of the generic arguments in an attempt to achieve a type like T | undefined
that doesn't allow values of type T
to be assigned to it. I understand that this may not be possible, but I thought I'd seek advice from the community instead of continuing to struggle on my own.
My objective here is: if I intend to pass an argument through a function like isNil
or ensure
, then I want to be compelled to update the argument type to be optional. If an argument is not optional, then I should be absolutely certain that there is no necessity to perform a null check on it.