Comparing at runtime and design time with typeof

TypeScript brings type in JavaScript, but this is mostly true at design type. TypeScript during compilation removes all the type. This is the reason that the code produced is purely JavaScript and does not contain any trace of interfaces or types. The purity of respect for JavaScript makes type comparison harder because it cannot rely on the name of the type to perform a type check. However, we can use all JavaScript's tricks to know whether a value is from a different type. The first feature answers the main question of this section about how to compare runtime and design type. The use of the JavaScript typeof operator that is present in JavaScript is also working the same way in TypeScript. The typeof operator returns the type of a primitive, or it returns object.

The usage is simple: call typeof followed by the variable that you want to compare it with. Most of the time, you will compare it to the name of the type that requires being written in a string:

const a = "test";
let b: number = 2;
const c: boolean = true;
let d: number | string = "test";
console.log(typeof a); // string
console.log(typeof b); // number
console.log(typeof c); // boolean
console.log(typeof d); // string

The typeof operator is especially used when having a union type where an object can be from many primitives. In fact, it can be used even with a union that has a complex object (interface or type) because typeof returns object:

const e: number | string | { complex: string, obj: number } = { complex: "c", obj: 1 };
console.log(typeof e); // object

To know which type of object the object is will require the use of other mechanisms that we will cover in this chapter. Before moving on, even if typeOf is comparable to a string, the result of the operation can be set a type:

let f: number = 2;
if (typeof f === "number") {
console.log("This is for sure a number");
}
type MyNewType = typeof f;

Note that typeOf works on primitive types but behaves strangely with undefined or null. However, undefined will return undefined and null will return object. The best approach to check for undefined or null is to not use typeof:

let g: number | undefined = undefined;
let h: number | undefined | null = null;
console.log(typeof g);
console.log(typeof h);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.125.205