Closed
Description
π Search Terms
assert types, type narrowing
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript 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, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
asserts return type of a function/method should also be able to return additional types as part of it.
- Maybe a limited form can be returning the type that's being asserted:
asserts x is T
also returnsx
(can also be written asx & asserts x is T
) - A more general form would be allowing assert functions to return arbitrary types with assertions:
fn(x: string | number): string asserts x is string
- Or maybe we could even support assertions on multiple arguments?
π Motivating Example
Use case:
I want the ability to narrow down this
in a class so that I can mimic some level of "extension methods".
π» Use Cases
- What do you want to use this for?
See use-case.
Another use-case is something I came up before (Asserts in constructor) section: #38442
- What shortcomings exist with current approaches?
Cannot be done.
- What workarounds are you using in the meantime?
For the motivating example, I have to create extension objects which adds extra runtime cost.