Skip to content

Suggestion: Controlflow with assertions, add ability for "throws" type guards #31512

Closed
@richardspence

Description

@richardspence

Search Terms Assert null, control flow strictNullChecks

Suggestion

With strict null checks turned on, I'd like to avoid the use of the escape operator ! when an assert library is used. The assert library ensures downstream statements are acting on initialized or otherwise constrained values. It would be great to provide hints to the compiler of the expected type narrowing as a result of the assertions.

Add a new way to define a typeguard that instructs the compiler that it would throw errors in certain scenarios. Syntax can be something like:
throws when [Existing type guard]

Use Cases

Using runtime assertion libraries/functions that correctly narrow the runtime types for subsequent statements.

Examples

//proposal for new control flow syntax "throws when..."
function assertNotNull(item: any): throws when item is undefined {
   if(!item){
      throw new Error();
   }
}

function doSomething(arg: string | undefined){
  //after invocation, all instances of arg should be treated as arg!
  assertNotNull(arg);

  //this should succeed
  var vals = arg.splt('');
}

Checklist

My suggestion meets these guidelines:

  • [ X] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [ X] This wouldn't change the runtime behavior of existing JavaScript code
  • [ X] This could be implemented without emitting different JS based on the types of the expressions
  • [X ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [ X] This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions