Description
Suggestion
Alternative title: "Require checked index access on any"
Require optional chaining for property access on any
typed values, possibly behind an extra flag or as a modification to the noUncheckedIndexedAccess
flag.
🔍 Search Terms
property access unknown optional chaining any strict checked index
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- If added behind a new flag.
- 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, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Currently, the any
type allows any operation, even unsafe ones that may throw at runtime. The alternative is unknown
which enforces checking, but is cumbersome to the point that it is often cast without sufficient checking, which is easy to do with type predicates or simply using as
.
Adding an option to require optional chaining when accessing properties of an any
value would remove one of the largest bug surface areas.
A previous proposal was made 2 years ago to allow optional chaining on unknown
values: #37700. This was rejected, and while I don't fully agree with the reasoning, I can see why it could be seen as incorrect. I believe requiring optional chaining for any
solves the same problem, while addressing the concerns in that proposal.
📃 Motivating Example
In vanilla JS, I would expect to see lots of optional chaining to defer type checking to the "leaf" node that is important. This change would check for good hygiene on a similar pattern in TS where a value is any
.
payload?.entries?.forEach?.((value) => ... );
A currently unsafe case in TS is JSON.parse, which returns an any
value that can lead to runtime failures. While an argument could be made that the failure is useful, most of the any
cases are from remote data which cannot be typed at compile time. In those cases its usually better to assume you might be out of sync with the source, and just provide defaults. In the cases where the source doesn't provide something that is definitely required, then it's best to check for just that condition, rather than validating the entire structure of a response.
const result = JSON.parse(bodyText);
// No type error, but potentially a runtime error when it should just be an unmatched condition.
if (result.error.code === 'NOT_FOUND') { ... }
// Should be fixed as follows, which is what this proposal would check.
if (result?.error?.code === 'NOT_FOUND') { ... }
Error handling is also a good example. In fact, this would make any
typed catch blocks safe to use in most cases.
try {
...
} catch (err: any) {
// No type error, but potentially a runtime error when it should just be an unmatched condition.
if (err.response.status === 401) { ... }
// Should be fixed as follows, which is what this proposal would check.
if (err?.response?.status === 401) { ... }
}
In the try/catch case, I explicitly typed err
as any
, which is (currently) considered not to be a good practice. However, I've seen many cases (like error handling) where an unknown
is cast to any
temporarily, specifically so that optional chaining can be used.
// This looks right at first glance, but the optional chain is missing between `response` and `status`.
// No type error will occur. If optional chaining were required for property access on any types, this
// would be a type error.
if ((err as any)?.response.status) { ... }
💻 Use Cases
Make safer usage required where any
is currently returned, for example values returned by JSON.parse
.
const response = await fetch(...);
const payload = await response.json();
if (response.ok) {
// This would now be a type error.
payload.entries.forEach((value) => ...);
// The type error would safely be resolved like this.
payload?.entries?.forEach?.((value) => ...);
} else { ... }
Error handling is currently fairly verbose for simple cases.
try {
...
} catch (err) {
if (typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT') { ... }
// Alternative
if ((err as null | undefined | { code: unknown }).code === 'ENOENT') { ... }
}
It could/should be this easy, while still being safe.
try {
...
} catch (err) {
if ((err as any)?.code === 'ENOENT') { ... }
}