Typescript is null or undefined

Null Vs Undefined in TypeScript

TypeScript has two special values for Null and Undefined. Both represent no value or absence of any value. The difference between Null & Undefined is subtle and confusing. Prior to TypeScript 2.0, we could assign them all other types like numbers, strings, etc. Such assignment has been the source of a lot of errors like TypeError s or ReferenceError s in JavaScript. The StrictNullChecks introduced in version 2.0 raises compile-time errors if we use Null or Undefined. In this tutorial, we compare Null and Undefined. let us learn the similarities and differences etc.

  • Undefined & Null
  • Undefined is the default value for uninitialized variables
  • Data Types
  • Setting the value
  • Falsy
  • Checking for Null & Undefined
  • Comparing Null with undefined
  • Arithmetic Operations
  • TypeOf
  • Summary
  • References

Undefined & Null

The value undefined means value is not assigned & you don’t know its value. It is an unintentional absence of value. It means that a variable has been declared but has not yet been assigned a value.

The value null indicates that you know that the field does not have a value. It is an intentional absence of value.

Читайте также:  Html div for layout

Undefined is the default value for uninitialized variables

Whenever we declare a variable without initializing it with a value, TypeScript initializes it as undefined . But TypeScript never assigns null to any variable. We have to assign Null to variable to make it null.

The following example declares the variable foo . We have not given it any initial value. By default, it gets the value undefined . But for null, we need to assign a value to it

Источник

how can a function check for null in typescript?

in typescript 2.6 I want to write a function that does a null check. When I enable strict null-checks, typescript 2.6 complains about the following code. (Note that when using the null check directly works) edited: corrected notNullOrUndefined since it didn’t check for foo

interface A < foo: string | undefined; >const notNullOrUndefined = (a: A): boolean => < return a.foo != null; >const len = (a: A): number => < //if (a.foo != null) < if (notNullOrUndefined(a))< return a.foo.length; >return 0; > 

seems like you should check if both a and a.foo are null or undefined. Something like const len = (a: A): number => a && a.foo && a.foo.length || 0;

4 Answers 4

EDIT: updated to reflect fixing a typo in question: The question is a little confusing, since your notNullOrUndefined() doesn’t check a.foo at all, so it’s not surprising that those would be different.

Note that with —strictNullChecks on, you have defined len() so that the a parameter is an A , and therefore cannot be null or undefined. So you don’t have to check a itself inside the len() function implementation; instead you need to make sure that anything you pass to len() is a valid A . So notNullOrUndefined() is kind of a bad name, since you’re checking the foo value of the parameter, not the parameter itself. Feel free to change it to something like fooPropertyIsNotNull() ; I will leave it for now.

The main issue here is that TypeScript recognizes that if (a.foo != null) < . >is a type guard, and narrows a.foo to string inside the < . >clause. But type guards do not propagate out of functions automatically, so TypeScript doesn’t understand that notNullOrUndefined() itself acts as a type guard.

Luckily, this issue is common enough that TypeScript provides user-defined type guards: if you have a function that returns a boolean which narrows the type of one of its parameters, you can change the boolean return type to a type predicate, using the x is T syntax. Here it is for notNullOrUndefined() :

const notNullOrUndefined = (a: A): a is < foo: string >=>

So the function signature says: if you pass in an A , it will return a boolean value. If it returns true , then the passed-in parameter is narrowed to < foo: string >. Now you will get no errors, as you wanted:

interface A < foo: string | undefined; >const notNullOrUndefined = (a: A): a is < foo: string >=> < return a.foo != null; // checking a.foo >const len = (a: A): number => < if (notNullOrUndefined(a))< return a.foo.length; // okay >return 0; > 

Hope that helps, good luck!

Источник

Typescript is null or undefined

Last updated: Jan 21, 2023
Reading time · 4 min

banner

# Correctly check for Null in TypeScript

To check for null in TypeScript, use a comparison to check if the value is equal or is not equal to null , e.g. if (myValue === null) <> or if (myValue !== null) <> .

If the condition is met, the if block will run.

Copied!
type Color = string | null; const color: Color = null; // ✅ Check if null if (color === null) console.log('value is equal to null'); > else console.log('value is NOT equal to null'); > // ✅ Check if NOT equal to null if (color !== null) console.log('value is NOT equal to null'); >

The first if statement checks if the color variable stores a null value.

The second example shows how to check if the variable is NOT null .

# Check for null or undefined implicitly in TypeScript

You might also see examples that use the loose equality (==) and loose inequality (!==) operators to check for null .

Copied!
type Color = string | null; const color: Color = null; // ✅ Check if a value is equal to null or undefined if (color == null) console.log('value is equal to null or undefined'); > // ✅ Check if a value is NOT equal to null or undefined if (color != null) console.log('value is NOT equal to null or undefined'); >

The first if statement uses the loose equals ( == ) operator instead of strict equals ( === ), and checks if the variable is equal to null or undefined .

This checks for both null and undefined because when using loose equals ( == ), null is equal to undefined .

Copied!
console.log(null == undefined); // 👉️ true

# The if statement serves as a type guard

The if statements above serve as a type guard in TypeScript.

Copied!
type Person = name: string | null; >; const person: Person = name: null, >; if (person.name !== null) // ✅ TypeScript knows person.name is string // 👇️ (property) name: string console.log(person.name); console.log(person.name.toLowerCase()); >

The name property on the Person type can either be a string or null .

In the if statement, we check if the property is not null .

If the condition is met, TypeScript knows that the only other possible type is a string and allows us to use string-specific methods like toLowerCase() .

If we try to call the toLowerCase() method directly, without checking if the property is not null , we’d get an error.

Copied!
type Person = name: string | null; >; const person: Person = name: null, >; // ⛔️ Error: 'person.name' is possibly 'null'. console.log(person.name.toLowerCase());

You could also use a type guard to check if the property is a string , which would be the more direct approach in this scenario.

Copied!
type Person = name: string | null; >; const person: Person = name: null, >; if (typeof person.name === 'string') // ✅ TypeScript knows person.name is string // 👇️ (property) name: string console.log(person.name); console.log(person.name.toLowerCase()); >

# Check for null using the optional chaining (?.) operator in TypeScript

You can also check if a variable is null or undefined by using the optional chaining (?.) operator.

Copied!
type Person = name: string | null; >; const person: Person = name: null, >; // 👇️ undefined console.log(person.name?.toLowerCase());

The optional chaining (?.) operator short-circuits and returns undefined if the value to the left is nullish ( null or undefined ).

This is why TypeScript allows us to check if the toLowerCase() method exists on the person.name property, even though it could be null .

If the variable is not null or undefined , the optional chaining (?.) operator returns the result of the operation.

Copied!
type Person = string | null; const person: Person = 'bobby hadz'; const result = person.toUpperCase(); console.log(result); // 👉️ BOBBY HADZ

You could also use this approach to check if a deeply nested property exists on an object.

Copied!
type Person = name?: first?: string | null; >; >; const person: Person = >; // 👇️ undefined console.log(person?.name?.first?.toLowerCase());

If the reference is equal to null or undefined , the optional chaining operator will short-circuit and return undefined and no error is thrown.

# Don’t use the typeof operator to check for null

The type of null is «object» in JavaScript, so you shouldn’t use the typeof operator to check for null .

Copied!
type Person = string | null; const person: Person = null; console.log(typeof person); // 👉️ "object"

It is an old bug that has not been fixed because it would cause breaking changes but the type of null is an «object» in JavaScript and TypeScript.

On the other hand, the type of undefined is «undefined» , so the operator works when checking for undefined .

Copied!
type Person = string | undefined; const person: Person = undefined; if (typeof person === 'undefined') // 👇️ this runs console.log('The variable is undefined'); >

The typeof operator returns a string that indicates the type of a value.

Copied!
console.log(typeof undefined); // 👉️ "undefined" console.log(typeof null); // 👉️ "object" console.log(typeof 'bobbyhadz'); // 👉️ "string"

Here is an example that checks if a variable is not undefined or null explicitly.

Copied!
type Person = string | undefined | null; const person: Person = 'bobbyhadz.com'; if (typeof person !== 'undefined' && person !== null) // 👇️ this runs console.log('succes'); >

Notice that we only used the typeof operator to check for undefined but we used an explicit comparison with null .

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью