Home > front end >  How to use is not type in TypeScript?
How to use is not type in TypeScript?

Time:10-31

How to use is not type in typescript?

example(just an example), I tried to use is not:

function notUndef(obj: any): obj is not undefined {
    return obj !== void(0);
}

and

function notUndef(obj: any): (typeof obj !== undefined) {
    return obj !== void(0);
} 

but I received two error:

Cannot find name 'not'.ts(2304)
'{' or ';' expected.ts(1144)

both of them doesn't work, what can I do?

CodePudding user response:

You may be looking for combining generics with the type predicate:

function notUndef<T>(obj: T): obj is Exclude<T, undefined> {
    return obj !== void(0);
}

CodePudding user response:

It's somewhat unclear what you're asking; I'm assuming you are trying to find a type signature for a method which checks that a variable has a value.

Correct code:

function notUndef(obj: any): boolean {
    return obj !== null && object !== undefined;//or obj !== void(0) if you prefer
}

Why this is correct:

The part after the colon tells TypeScript the data type of the return value, not the meaning of the return value. You are evaluating an expression which will be either true or false, so the returned value will be true | false (which is equivalent to the built-in type boolean). What that value means in the context of your program is something you will have to track through good variable and function names, as well as documentation such as comments. You can sometimes use types for this as well, but you would need to create a custom type and for this case it seems most likely not worth it.

  • Related