Refinement of optional properties should use the `in` operator (and know a property is present, even if potentially null)
- Dominant language
- Rust
- Stars
- 22.3k
- Forks
- 1.9k
- PR merge metrics
- No merged PRs in 30d
Description
Problem case:
```jsx
type MyObj = {
value?: V
};
function getValue(obj: MyObj, defaultValue: V): V {
if ('value' in obj) {
return obj.value;
}
return defaultValue;
}
```
Currently there is an error:
```
Cannot return `obj.value` because undefined [1] is incompatible with `V` [2]
```
But this is not true - inside that `if` block, `obj.value` can only be undefined if `V` happens to be undefined (in which case, the return type of `V` would be compatible).
There needs to be a way of dealing with optional props that is distinct from maybe-values. Generic types lets you have functions that operate on ANY value. That includes `null` and `undefined`. Sometimes that is the value we are operating on, and we still want to make the distinction between that and "actually, no value was given".
A similar case could be made about the distinction between optional function arguments and maybe-value arguments, though the mechanism for distinguishing between is far more awkward (`arguments.length` I guess?).
Contributor guide
Assessment
This issue has not been assessed yet.