Skip to content

Suggestion: Type guarding by means of property checking #3740

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
AbubakerB opened this issue Jul 4, 2015 · 2 comments
Closed

Suggestion: Type guarding by means of property checking #3740

AbubakerB opened this issue Jul 4, 2015 · 2 comments

Comments

@AbubakerB
Copy link
Contributor

Hi guys,

In regards to type guards, one thing that is fairly common in the javascript world is checking a property to see if its a certain type.

var variable: number | boolean[] | string;
if (variable.length) {
    // variable is of type boolean[] | string  
}
else {
    // variable is of type number
}

Would this be a possible thing to include in typescript?

One thing i see as an issue/blocker (probably why this hasn't already been implemented) is that length isn't a valid property of variable.
But i thought, just like how we can opt out of a strongly typed var with the any keyword, maybe we could "flatten" out a union type to show all it's properties.
I suggest doing something like so: (<all>variable).length or maybe variable?.length (or something else?)

In fact, i already implemented the latter, and it works great, but of course, ?. might be used for something else in the future (hint: C# 6). Maybe we can discuss this.

Where do the TS team stand on this?

@RyanCavanaugh
Copy link
Member

See #1260

@AbubakerB
Copy link
Contributor Author

I guess i didn't search good enough... my bad! 😄
I'll close this and move the discussion over there

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants