Categories
JavaScript TypeScript

TypeScript Data Types – Null, Void, Undefined, Never and Object

JavaScript, like any other programming language, has its own data structures and types.

JavaScript has a few data types that we have to know, to build programs with it. Different pieces of data can be put together to build more complex data structures.

JavaScript is a loosely typed, or dynamically typed, language. This means that a variable that’s declared with one type can be converted to another type without explicitly converting the data to another type.

Variables can also contain any type at any time, depending on what’s assigned. With dynamically typed languages, it’s hard to determine the type that a variable has without logging it and we might assign data that we don’t want in the variable.

TypeScript rectifies these issues by letting us set fixed types for variables so that we’re sure of the types. In this article, we’ll look at the void, null, undefined, never, and the object types.


Void

The void type is pretty much the opposite of the any type. It means the absence of any type. So, the variable of the void type can only have the value null if the --strictNullChecks setting isn’t specified when running the TypeScrip compiler or it can be set to undefined.

Therefore, directly assigning values to a void variable isn’t very useful. It’s more used for specifying the return data type of a function. A function that has the void return type doesn’t return anything.

For example, we can do a useless assignment to a void variable like in the following code:

let useless: void = undefined;

We can set the return type of an arrow function to void by writing:

const voidFn = (): void => {  
  console.log("Void function returns nothing");  
}
voidFn();

Alternatively, we can set the return type to void for a traditional function like in the following code:

function voidFn(): void {  
  console.log("Void function returns nothing");  
}
voidFn();

Both function calls will output Void function returns nothing from the console.log statement inside the function.


Null

The null type represents a variable that can only take on the value null. null means that there’s no value for a variable.

So, once again, assigning a value to it is pretty useless. We can only assign null to a variable that has the variable null. With the --strictNullChecks flag set when running the TypeScript compiler, null can only be assignable to variables with the any type and the null type.

Where it does become useful is that we can have variables that can have values from more than one assigned to it with union types.

Then, we can specify something useful along with the null type. This is different from JavaScript in that the value null is the type object instead of null for historical reasons.


Undefined

The undefined type represents a variable that can only take on the value undefined. So, once again, assigning a value to it is pretty useless.

We can only assign undefined to a variable that has the variable null. undefined can only be assignable to variables with the any type and the undefined type.

Where it does become useful is that we can have variables that can have values from more than one assigned to it with union types.

Then, we can specify something useful along with the undefined type. It’s practically useless on its own, so we shouldn’t see many cases with variables that have only the undefined type.


Never

The never type is a type of value that represents something that never occurs. It’s like void in that it’s useful for designating that a function never returns anything.

The never type is a sub-type of, and is assignable to, every type. However, no type is a sub-type of, or assignable to, the never type except for other never variables.

A function that has a never return type must always have an unreachable endpoint. For example, we can write a function that has an infinite loop that has the never return type like in the following code:

function infiniteFn(): never {  
  while (true) {  
  }  
}

A function that throws an exception may also have the never return type, like in the following example:

function errorFn(message: string): never {  
  throw new Error(message);  
}
errorFn('Error occurred');

Object

The object type is a type that represents non-primitive objects. That is, anything that’s not a number, string, boolean, bigint, symbol, null, or undefined.

It’s mainly used in the type definition of the Object object in the standard library and other pieces of code that don’t want primitive values to be assigned to it, or passed into a function.

For example, in the type definition of the Object.create method, we see that the type of the parameter is set to the object like in the following code:

create(o: object | null): any;

Likewise, in the signature of the setPrototypeOf method in the same type declaration, we see that the proto parameter, which is the parameter that takes the prototype of an object, also has the object type set, as it does below:

setPrototypeOf(o: any, proto: object | null): any;

This way, we can’t pass in primitive values into these methods as arguments in TypeScript. If we did, then we would get an error. So, if we have the following code in our TypeScript files, then they would be compiled and run:

const obj1 = Object.create({});      
const obj2 = Object.create(null);  
console.log(obj1);  
console.log(obj2);

We would get an empty object in both console.log statements.

The only difference is that obj2 is a pure object, which means it doesn’t inherit from any prototype. Passing in primitive values to the create method like in the code below will cause compilation to fail:

Object.create(42);   
Object.create("abc");   
Object.create(false);  
Object.create(undefined)

The code above would get us an Argument of type ‘42’ is not assignable to parameter of type ‘object | null’ error for the first one, Argument of type ‘abc’ is not assignable to parameter of type ‘object | null’ for the second one.

The third line would get us Argument of type ‘false’ is not assignable to parameter of type ‘object | null’, and the last line would get us Argument of type ‘undefined’ is not assignable to parameter of type ‘object | null’.

Compilation would fail and the code wouldn’t run.

Also, we can use it to prevent primitive values from being assigned to it. For example, if we write:

let x: object = {};

Then, the code above would be compiled and run. However, if we write the following instead:

let x: object = 1;

Then we get Type ‘1’ is not assignable to type ‘object’ and the code can’t be compiled with the TypeScript compiler and be run, since 1 is a primitive value.

The void type is pretty much the opposite of the any type. It means the absence of any type. So, the variable of the void type can only have the value null if the --strictNullChecks setting isn’t specified when running the TypeScrip compiler or it can be set to undefined.

It’s useful for declaring functions that don’t return anything and not much else. The null type variable can only take on the null value. The undefined type can only be assigned the value undefined.

The object type is a type that represents non-primitive objects. That is, anything that’s not a number, string, boolean, bigint, symbol, null, or undefined.

It’s mainly used in the type definition of the Object object in the standard library and other pieces of code that don’t want primitive values to be assigned to it, or passed into a function.

Categories
JavaScript TypeScript

TypeScript Data Types – Numbers, Strings, and Objects

JavaScript, like any other programming language, has its own data structures and types. JavaScript has a few data types that we have to know about in order to build programs with it. Different pieces of data can be put together to build more complex data structures.

JavaScript is a loosely typed, or dynamically typed, language. This means that a variable that’s declared with one type can be converted to another type without explicitly converting the data to another type. Variables can also contain any type at any time, depending on what’s assigned.

With dynamically typed languages, it’s hard to determine the type that a variable has without logging it, and we might assign data that we don’t want in the variable.

TypeScript rectifies these issues by letting us set fixed types for variables so that we’re sure of the types. It has all the basic data types of JavaScript plus the types that are exclusive to TypeScript, like numbers, strings, and objects.


Numbers

There are two number types in JavaScript, which are number and BigInt. The number type is a double-precision 64-bit number that can have values between -2 to the 53rd power minus 1 and 2 to the 53rd power minus 1. There’s no specific type for integers. All numbers are floating-point numbers. There are also three symbolic values: Infinity, -Infinity, and NaN.

The largest and smallest available values for a number are Infinity and -Infinity, respectively. We can also use the constants Number.MAX_VALUE or Number.MIN_VALUE to represent the largest and smallest numbers. We can use the Number.isSafeInteger() function to check whether a number is in the range of numbers available that are allowed in JavaScript.

There are also the constants Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_NUMBER to check if the number you specify is in the safe range. Anything outside the range isn’t safe and will be a double-precision floating-point of the value. The number 0 has two representations in JavaScript: There’s +0 and -0, and 0 is an alias for +0. It will be noticed if you try to divide a number by 0:

1/+0 // Infinity  
1/-0 // -Infinity

Sometimes numbers can represent Boolean values with bitwise operators to operate them as Boolean, but this is bad practice since JavaScript already has Boolean types, so using numbers to represent Boolean will be unclear to people reading the code. That’s because numbers can represent numbers, or they can represent Booleans if someone chooses to use them that way.

We can declare numbers like in the following code with TypeScript:

const x: number = 1  
const y: number = x + 1;

In TypeScript, there is the BigInt type to store numbers that are beyond the safe integer range. A BigInt number can be created by adding an n character to the end of a number. With BigInt, we can make calculations that have results beyond the safe range of normal numbers. For example, we can write the following expressions and still get the numbers we expect:

const x: bigint = 2n ** 55n;  
const y: bigint = x + 1n;

For x we get 36028797018963968n and for y we get 36028797018963969n, which is what we expect. BigInts can use the same arithmetic operations as numbers, such as +, *, -, ** and %. A BigInt behaves like a number when converted to a Boolean, with functions, keywords, or operators like Boolean, if , || , &&, !. BigInts cannot be operated in the same expressions as numbers. If we try that, we will get a TypeError. This is enforced with TypeScript compiler checks before compilation is done.


Strings

Strings are used to represent textual data. Each element of the string has its own position in the string. It’s zero-indexed, so the position of the first character of a string is 0. The length property of the string has the total number of characters of the string.

JavaScript strings are immutable. We cannot modify a string that has been created, but we can still create a new string that contains the originally defined string. We can extract substrings from a string with the substr() function and use the concat() function to concatenate two strings.

We should only present text data with strings. If there are more complex structures needed for your data structure, then they shouldn’t be represented with a string. Instead, they should be objects. This is because it’s easy to make mistakes with strings since we can put in the characters we want.

We can declare strings in TypeScript with the following code:

const x: string = 'abc';

Objects

Object is a reference data type, which means it can be referenced by an identifier that points to the location of the object in memory. In memory, the object’s value is stored, and, with the identifier, we can access the value. Object has properties, which are key-value pairs with the values being able to contain the data with primitive types or other objects.

That means we can use object to build complex data structures. The key is an identifier for the values of a property, which can be stored as a string or symbol. There are two types of properties that have certain attributes in an object. Objects have data properties and accessor properties.

A JavaScript object has the following data properties:

  • [[Value]] — This can be of any type. It has the value retrieved by a getter of the property. Defaults to undefined.
  • [[Writable]] — This is a Boolean value. If it’s false, then [[Value]] can’t be changed. Defaults to false.
  • [[Enumerable]] — This is a Boolean value. If it’s true, then it can be iterated over by the for...in loop, which is used to iterate over the properties of an object. Defaults to false.
  • [[Configurable]] — This is a Boolean value. If it’s true, then the property can be deleted or changed to an accessor property, and all attributes can be changed. Otherwise, the property can’t be deleted or changed to an accessor property, and attributes other than [[Value]] and [[Writable]] can’t be changed. Defaults to false.

A JavaScript object has the following accessor properties:

  • [[Get]] — This is either a function or it’s undefined. This may contain a function that is used to retrieve a property value whenever a property is being retrieved. Defaults to undefined.
  • [[Set]] — This is either a function or it’s undefined . This lets us set the assigned value to an object’s property whenever an object’s property is attempted to be changed. Defaults to undefined.
  • [[Enumerable]] — This is a Boolean value that defaults to false. If it’s true, then the property will be included when we loop through the properties with the for...in loop.
  • [[Configurable]] — This is a Boolean value that defaults to false. If it’s false, then we can’t delete the property and can’t make changes to it.

JavaScript has a Date object built into the standard library, so we can use it to manipulate dates.

Array are also objects. Array can store a list of data with integer indexes to indicate its position. The first index of JavaScript arrays is 0. There’s also a length property to get the size of the array. The Array object has many convenient methods to manipulate arrays, like the push method to add items to the end of the array and the indexOf method to find the index of the first occurrence of a given value. ATypedArray object is an object that lets us see an array-like view of a binary data buffer.

Since ES2015, the following typed array objects are available:

  • Int8Array, value ranges from -128 to 127
  • Uint8Array, value ranges from 0 to 255
  • Uint8ClampedArray, value ranges from 0 to 255
  • Int16Array, value ranges from -32768 to 32767
  • Uint16Array, value ranges from 0 to 65535
  • Int32Array, value ranges from -2147483648 to 2147483647
  • Unit32Array, value ranges from 0 to 4294967295
  • Floar32Array, value ranges from -1.2 times 10 to the 38 to 3.4times 10 to the 38
  • Float64Array, value ranges from 5.0 times 10 to the 324 to 1.8 times 10 to the 308
  • BigInt64Array, value ranges from -2 to the 63 to 2 to the 63 minus 1
  • BigUint64Array, value ranges from 0 to 2 to the 64 minus 1

Since ES2015, we have new iterable object types. They are Map, Set, WeakMap, andWeakSet. Set and WeakSet represent sets of objects, and Map and WeakMap represent objects with a list of key-value pairs. Map keys can be iterated over, butWeakMap’s keys cannot be.

With TypeScript, we put constructor names after the colon in the variable declaration to declare their types. For example, if we want to declare a Map object, we can write:

const map: Map<string, number> = new Map([['a', 1], ['b', 2]]);

Note that the way to declare some objects like Maps is different from JavaScript. This is because TypeScript supports generics. Generics in TypeScript allows us to pass in an indeterminate type to functions, interfaces, and classes (which are just syntactic sugar for functions) so that the actual type can be passed as we reference the object in the code, as we did above. The declaration above is type-safe, unlike the JavaScript way to declare Map objects. With the code above, the keys of the Map are always strings and the values are always numbers.

With dynamically typed languages, it’s hard to determine the type that a variable has without logging it, and we might assign data that we don’t want in the variable like JavaScript. TypeScript rectifies these issues by letting us set fixed types for variables so that we’re sure of the types. It has all the basic data types of JavaScript plus the types that are exclusive to TypeScript. We’ll go into more details in other TypeScript articles, where we will explore TypeScript-only data types, interfaces, combining multiple types, and more.