Skip to content

type assertion should support additional return typeΒ #61142

Closed
@zen0wu

Description

@zen0wu

πŸ” Search Terms

assert types, type narrowing

βœ… Viability Checklist

⭐ 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 returns x (can also be written as x & 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".

Here's a playground link: https://www.typescriptlang.org/play/?#code/MYGwhgzhAECyD2ATApiAPPArgF2gFQD5oBvAKGgugDswAnW+Adz3gGVtaBLKgcwAoAlAC5okCMlrYY2ABacY8uElRoIHbjyJlKO6LWTZMtKtA6Zk5SgF9Slimq69YBmUgCMfWfJEIU6BxoEAiQ2NqTA8FRq0AAe0AC81MiMSn5oVJgAtgBGEtAAPtABvASCpAD05fhyMBCumCCI0ABmYJwgAHSkMR3FPM6y7mUVVQCS0IxgVLjY8NC5otkgyKZziHNeEF09NPRMLOyO-AK96k4uQwKkQA

πŸ’» Use Cases

  1. 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

  1. What shortcomings exist with current approaches?

Cannot be done.

  1. What workarounds are you using in the meantime?

For the motivating example, I have to create extension objects which adds extra runtime cost.

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