Description
Search Terms
Optional chaining, unknown
Suggestion
Currently it is forbidden to use optional chaining on unknown
. But for all possible types in JavaScript, optional chaining will return undefined
if it does not apply or cannot find the field. So we should safely regard optional chaining of unknown
type to be unknown
as well.
This is the verification of optional chaining on all possible types in JavaScript:
const num = 5;
const str = '6';
const undef = undefined;
const nul = null;
const bool = true;
const sym = Symbol('sym');
const obj = {};
const func = () => {};
console.log(num?.field); // print undefined
console.log(str?.field); // print undefined
console.log(undef?.field); // print undefined
console.log(nul?.field); // print undefined
console.log(bool?.field); // print undefined
console.log(sym?.field); // print undefined
console.log(obj?.field); // print undefined
console.log(func?.field); // print undefined
Use Cases
This is to simplify type checking on nested object with unknown type. For example, we should be able to do something like this:
function getFieldFromJson(json: unknown): undefined | number {
const field = json?.fieldA?.fieldB?.fieldC; // <--- this
if (typeof field === 'number') {
return field;
}
}
Currently we will need to cast explicitly on someUnknown
, someUnknown.fieldA
, someUnknown.fieldA.fieldB
and someUnknown.fieldA.fieldB.fieldC
. People will find this is unnecessary verbose and may just fallback to use any
.
Examples
As above
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.