The typeof operator

The typeof operator is used to check the type of a given operand. You can use the operator to control the harm of loose types. Let's see some examples:

// Code 1.5function greetUser( username ) { if(typeof username !== 'string') {   throw new Error('Invalid type passed'); }; var reversed = username.split('').reverse().join(''); return `Hi, ${reversed}`}console.log('Greet a correct user: ', greetUser('Codebeast'))console.log('Greet a boolean: ',greetUser(true))

Rather than waiting for the system to tell us that we're wrong when an invalid type is passed in, we catch the error as early as possible and throw a custom and more friendly error, as shown in the following screenshot:

The typeof operator returns a string, which ...

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.