Type Operators in TypeScript with Examples

What are Type Operators in TypeScript?

In TypeScript, the Type operators in programming languages are used to determine the data type of a variable or an expression.

They return a string that represents the data type.

Type Operators are utilized with objects or aid in handling objects, such as typeof, instanceof, in, or delete, are typically classified under the category of Type operators.

List of Type Operators

Here are the list of Type Operators with examples.

1. in operator

The in verifies whether a property exists on an object.

Here’s an example:

let car = {
    brand: "Toyota",
    model: "Camry",
    year: 2024
};

// Using the 'in' operator
let hasMakeProperty = "brand" in car;

console.log(hasMakeProperty);

Outputs:

true

2. typeof operator

The typeof operator is used to get the data type of a variable or an expression.

Let’s take a look at the example:

let message = "Hi, welcome to Itsourcecode!";
console.log(typeof message);

Outputs:

string

Here’s another example:

let age= 18;
console.log(typeof age); 

Output:

number

3. instanceof operator

The instanceof operator determines whether the object belongs to a specific type.

Let’s take a look at the example:

const A: String = new String('Hi, Welcome to Itsourcecode!');
console.log(A instanceof String);

Output:

true

4. delete operator

The delete operator deletes or removes properties from objects

Let’s take a look at the example:

// Define an object
let employee = {
    name: "ItSourceCode",
    age: 18,
    Position: "Programmer"
};
console.log(employee); 

Output:

{ name: 'ItSourceCode', age: 18, Position: 'Programmer' }

Now, let’s use the delete operator:

// Define an object
let employee = {
    name: "ItSourceCode",
    age: 18,
    Position: "Programmer"
};


// Use the delete operator
delete employee.Position;

console.log(employee); 

Output:

{ name: 'ItSourceCode', age: 18 }

Conclusion

So, that’s the end of our discussion about the Type operators, which is used to determine the data type of a variable or an expression.

They return a string that represents the data type.

Type Operators are utilized with objects or aid in handling objects, such as typeof, instanceof, in, or delete, are typically classified under the category of Type operators.

I hope this article has provided you with insights and helped you understand the Type Operators TypeScript.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment