microsoft / microsoft/TypeScript

Disallowing `throw`ing expressions that aren't assignable to `Error`

Open
#33,596 3 comments 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Search Terms

throw, throwing non-error

Suggestion

Add typechecking to throw statement, allowing it to only throw Errors and anys.

Code currently allowed, but with strong potential for bugs:

throw null;
throw undefined;
throw 'foobar';
throw ''; 
throw 42;
throw {foo: 'bar'};
throw potentiallyNullable; // with –strictNullChecks

After implementing this feature request, such code wouldn't be allowed.

Use Cases

Even if it's possible to throw non-errors in JavaScript code, it's extremely confusing and hard to debug. Failing to properly handle such cases happened even to Mozilla.

Examples

Forbidden code:

throw null;
throw undefined;
throw 'foobar';
throw 42;
throw {foo: 'bar'};
throw potentiallyNullable; // with –strictNullChecks

Allowed:

throw new Error();
throw null as any;

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code - it can break existing TypeScript 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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue provides no file or test path. Start by locating throw-statement type checking in the TypeScript compiler and its tests, then review how nullable and any expressions are handled. Done means the listed non-Error expressions are rejected while Error and any expressions remain allowed, without changing emitted JavaScript.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.