Skip to content

Suggestion: a Type Assertion that asserts at run time #2444

@neilgalarneau

Description

@neilgalarneau

Type Assertions are compile time only.

It would be helpful to have a concise way to have a compile time type assertion be checked at run time.

The language spec gives the example:

var shape = createShape(shapeKind);
if (shape instanceof Circle) { 
  var circle = <Circle> shape;
  ...
} else {
  throw new WrongTypeAssertionException("Wanted type Circle, but was actually " + (typeof shape));
}

which is very repetitive (and fragile). Instead it would be great to have something much more concise like:

var circle = <Circle!> createShape(shapeKind);

that threw an exception at run time if an instanceof check failed.

I would rather give up some run time performance for a concise way to get a clear run time failure message if my assertion is false.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions