In TypeScript, you can use the typeof keyword to check for basic types (that is, number, string, boolean, and more). If you perform such a check in an if statement, then, inside the block, TypeScript will know whether the type matches and will consider the variable to be of that type. The following example will make this clearer:
let hello = "Hello"; function saySomething(something: any): void { if(typeof something === "string") { console.log(`You passed in a string; its first character is:
${something.charAt(0)}`); } else if(typeof something === "number") { console.log(`You passed in a number: ${something}`); } else{ console.log(`You didn't pass in a string or number. Type of
the given element: ${typeof something}`); } } saySomething("Hello"); saySomething(42); saySomething({foo: "Bar"});
As you can see in the preceding example, once we're in a block where the type has been checked, although any was passed in, TypeScript then knows the exact type and treats the object accordingly. In the preceding code, it allows us to use the charAt string method directly.
typeof is especially useful for strings and numbers.
You can learn more about typeof here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof.