November 2019
Beginner
804 pages
20h 1m
English
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}`); ...Read now
Unlock full access