Query Synopsis
My aim is to restrict explicit values of undefined
while permitting implicit undefined
values.
Context
In the realm of JavaScript, there exists a scenario where attempting to access a nonexistent key results in undefined
, similarly, accessing an existing key may also yield undefined
.
For instance,
[1, 2, undefined, 4][2]
->undefined
[1, 2, 3, 4][99]
->undefined
{a: 1, b: undefined}.b
->undefined
{a: 1, b: 2}.foo
->undefined
.
The first and third examples explicitly access undefined
values, whereas the second and fourth examples implicitly access undefined
values.
Query Statement
The task at hand is to designate a key that may or may not be present (optional), with the condition that if it does exist, it cannot be undefined
. Is this feasible?
Additional Context
// - mustExistAndCouldBeUndefined must be present in this type, but it may be undefined.
// - couldExistAndCouldBeUndefined may be present in this type. If present, it can be undefined. If absent, it's undefined.
// - couldExistButCannotBeUndefinedIfItDoes may be present in this type. If present, it cannot be undefined. If absent, it's undefined.
type Example = {
mustExistAndCouldBeUndefined: number | undefined;
couldExistAndCouldBeUndefined?: number;
??? couldExistButCannotBeUndefinedIfItDoes ???
};
// I want this to be allowed, since couldExistButCannotBeUndefinedIfItDoes is permitted to be absent (implicitly undefined).
const a: Example = {
mustExistAndCouldBeUndefined: undefined,
};
// I want this to be DISALLOWED as couldExistButCannotBeUndefinedIfItDoes is not permitted to exist and be undefined (explicitly undefined).
const b: Example = {
mustExistAndCouldBeUndefined: undefined,
couldExistButCannotBeUndefinedIfItDoes: undefined,
};
Is there a way to implement a concept similar to
couldExistButCannotBeUndefinedIfItDoes
as seen in the code snippet above?