Skip to content
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

Inline condition type narrow #47174

Closed
5 tasks done
behnammodi opened this issue Dec 17, 2021 · 3 comments
Closed
5 tasks done

Inline condition type narrow #47174

behnammodi opened this issue Dec 17, 2021 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@behnammodi
Copy link

behnammodi commented Dec 17, 2021

Suggestion

πŸ” Search Terms

Inline condition type narrow

βœ… Viability Checklist

My suggestion meets these guidelines:

  • 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 feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Well, if we have type narrow front of condition this would be very helpful

if (typeof thing.x === 'number'): thing is A {
  ...

πŸ“ƒ Motivating Example

This is very helpful to reduce redundant code for type narrow, without that we have to write a function to check type:

...
const isA = (thing: A | b): thing is A => typeof thing.x === 'number';

if (isA(thing)) {
    console.log(thing.x + 1);
}
...

πŸ’» Use Cases

class A {
    x: number = 0;
}

class B {
    x: string = ""; 
}

const thing: A | B = {} as any;

if (typeof thing.x === 'number'): thing is A {
    console.log(thing.x + 1);
}
@MartinJohns
Copy link
Contributor

Duplicate of #41710, which was marked a duplicate of #6474.

@fatcerberus
Copy link

For the record, this is no safer than just using a type assertion, since the type predicate isn’t checked (if it could be checked, you wouldn’t need it). The same goes for type guard functions, but those at least are reusable.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 4, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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

5 participants