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

Suggestion: is not typegaurd #9378

Closed
speigg opened this issue Jun 27, 2016 · 6 comments
Closed

Suggestion: is not typegaurd #9378

speigg opened this issue Jun 27, 2016 · 6 comments
Labels
Duplicate An existing issue was already created

Comments

@speigg
Copy link

speigg commented Jun 27, 2016

To support the following use case, for example:

function defined(value: any): item isnot undefined|null { // "isnot" or "is not" ?
    return value !== undefined && value !== null
}

This would be particularly useful when combined with strictNullChecks:

var value:string;
function setValue(value: string|undefined) {
    if (defined(value)) {
        value = value; // currently causes an error, since tsc believes value is still possibly undefined
    } else {
        value = "default";
   }
}
@RyanCavanaugh
Copy link
Member

I think you want #1809 because then you could just write

type Defined = string | number | boolean | object;
function defined(value: any): value is Defined { return value != null; }

@speigg
Copy link
Author

speigg commented Jun 27, 2016

Oh yeah, that would work nicely. Any reason the following wouldn't work?

type Defined = string | number | boolean | {};
function defined(value: any): value is Defined { return value != null; }

I thought the "{}" type was effectively "object", but the link you pointed me at seems to suggest otherwise.

@speigg
Copy link
Author

speigg commented Jun 27, 2016

Or if I understand correctly, perhaps I can just use the {} type alone...

function defined(value: any): value is {} { return value != null; }

About to try this.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Jun 27, 2016
@mhegazy
Copy link
Contributor

mhegazy commented Jun 27, 2016

you can achieve this today using generic types, as such:

function defined<T>(value: T | undefined | null): value is T { return value != null; }

@aluanhaddad
Copy link
Contributor

@mhegazy beat me to it, I was about to post

function isDefined<T>(x: T | undefined | null): x is T {
    return x != undefined;
}

@speigg
Copy link
Author

speigg commented Jun 27, 2016

Thanks guys, all of these solutions work great, including value is {}. I like the generics though, I'll use that!

@speigg speigg closed this as completed Jun 27, 2016
@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants