Skip to content

type assertion should support additional return type #61142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
6 tasks done
zen0wu opened this issue Feb 7, 2025 · 1 comment
Closed
6 tasks done

type assertion should support additional return type #61142

zen0wu opened this issue Feb 7, 2025 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@zen0wu
Copy link

zen0wu commented Feb 7, 2025

πŸ” 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.

@MartinJohns
Copy link
Contributor

// I want to be able to do this.
x.narrowToString().stringMethod1()

This is clearly out of scope for TypeScript. The narrowToString() method returns a boolean, and that type does not have a stringMethod1(). TypeScript would need to rewrite the code, which is out of scope.

Other than that it sounds like a duplicate of #40562.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Feb 7, 2025
@zen0wu zen0wu closed this as completed Feb 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants