Skip to content

Require optional chaining for any type property access. #53438

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
5 tasks done
Shakeskeyboarde opened this issue Mar 22, 2023 · 6 comments
Closed
5 tasks done

Require optional chaining for any type property access. #53438

Shakeskeyboarde opened this issue Mar 22, 2023 · 6 comments
Labels
Declined The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript

Comments

@Shakeskeyboarde
Copy link

Shakeskeyboarde commented Mar 22, 2023

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') { ... }
}
@Shakeskeyboarde
Copy link
Author

Does not directly address, but would reduce the need for #13219.

@MartinJohns
Copy link
Contributor

MartinJohns commented Mar 22, 2023

Currently, the any type allows any operation, even unsafe ones that may throw at runtime.

That is the very purpose of any.

I think your suggestion might be better suited as a linter rule.

@RyanCavanaugh
Copy link
Member

You can represent this type today if that's your goal:

interface SafeRecord {
    [s: string]: SafeRecord;
};

declare let q: SafeRecord;
const m = q?.r?.s?.t;

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript Declined The issue was declined as something which matches the TypeScript vision labels Mar 22, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Declined" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 21, 2023
@benbenbenbenbenben
Copy link

benbenbenbenbenben commented Feb 21, 2024

You can represent this type today if that's your goal:

interface SafeRecord {
    [s: string]: SafeRecord;
};

declare let q: SafeRecord;
const m = q?.r?.s?.t;

This should be:

interface SafeRecord {
  [s: string]: SafeRecord | undefined;
};

eg.

interface SafeRecord {
  [s: string]: SafeRecord | undefined;
};

declare let q: SafeRecord;
const m = q?.r?.s?.t?.u?.v?.w?.x?.y?.z?.a;

// inline use of typeof doesn't work, so you need to define a type guard
const IsString = (s: unknown): s is string => typeof s === "string";
const IsNumber = (s: unknown): s is number => typeof s === "number";

if (IsString(m)) {
  console.log(`m is a string: ${m} `);
}
else if (IsNumber(m)) {
  console.log(`m is a number: ${m} `);
}
else {
  console.log("m is not a string or a number ");
}

@RyanCavanaugh
Copy link
Member

If you want this behavior, surely you should have noUncheckedIndexedAccess on, which makes the | undefined unnecessary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Declined The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

5 participants