Typescript: Add an "argument is not type" operator

Created on 28 Jun 2017  路  9Comments  路  Source: microsoft/TypeScript

We already have:

function isNotUndefined(obj:any): obj is string | number | boolean | MyCustomType | null | MyOtherCustomType {
    return typeof obj !== "undefined";
}

Now we just need:

```ts
function isNotUndefined(obj:any): obj is not undefined { // or isnot
return typeof obj !== "undefined";
}

Question

Most helpful comment

function isNotUndefined<T>(obj: T | undefined): obj is T {
    return typeof obj !== "undefined";
}
var x = Math.random() > 0.5 ? undefined : 32;
if (isNotUndefined(x)) {
    console.log(x.toFixed());
}

All 9 comments

Dupe (or heavily related to) #4183

function isNotUndefined<T>(obj: T | undefined): obj is T {
    return typeof obj !== "undefined";
}
var x = Math.random() > 0.5 ? undefined : 32;
if (isNotUndefined(x)) {
    console.log(x.toFixed());
}
const test: (string | undefined)[] = []
test.filter(<T>(a: T): a is T | undefined => { 
    return !!a; 
}).map(t => {
    // t is string | undefined
})

@Arlen22 why did you write the predicate wrong? This works in 2.4:

const test: (string | undefined)[] = []
test.filter(<T>(a: T | undefined): a is T => { 
    return !!a; 
}).map(t => {
    t;
    // t is string
})

Strange. In 2.4.1:

const test: (string | undefined)[] = []
test.filter(<T>(a: T | undefined): a is T => { 
    return !!a; 
}).map(t => {
    let r: string = t; //Error: Type 'string | undefined' is not assignable to type 'string'
})

Nevermind, I forgot to update my global tsc. Now I'm seeing the new feature. Nice :)

Any idea what PR brought this in?

11858

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings