How to Check If a Variable is a String in TypeScript [4 Ways]

Here are the ways to check if a variable is a string in TypeScript:

  1. TypeScript Types
  2. Using the typeof Operator
  3. Using the instanceof Operator
  4. Using Object.prototype.toString() method

Method 1: Using TypeScript Types

In TypeScript, you can specify types for variables when you declare them. If you specify a type for a variable, TypeScript will ensure that only values of that type can be assigned to that variable.

Example

let myVar: string;

myVar = "Hello, World!"; 
myVar = 123;

console.log(myVar)

Output

Using TypeScript Types

Method 2: Using the typeof operator

The typeof operator in TypeScript is “used to check the type of a variable at runtime.” If a variable is a string, typeof will return the string “string”.

Syntax

typeof <operand>

Return value

The operator returns a string that denotes the type of the operand.

Example

let myVar: any = "Hello, World!";

if (typeof myVar === "string") {
  console.log("myVar is a string");
} else {
  console.log("myVar is not a string");
}

Output

myVar is a string

Method 3: Using an instance operator

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object. However, this approach is more commonly used with custom objects and classes and may not be as straightforward for primitive types like strings. For strings, it’s more common to use “typeof”.

Syntax

<object> instanceof <constructor/type>

Return value

It returns a boolean value. In addition, the operator accepts only object instances, not the primitives.

Example

let myVar: any = new String("Hello, World!");

if (myVar instanceof String) {
  console.log("myVar is a string object");
} else {
  console.log("myVar is not a string object");
}

Output

myVar is a string object

Method 4: Using the Object.prototype.toString() method

Another way to check if a variable is a string is to use the Object.prototype.toString() method. This method returns a string representing the object’s type.

Syntax

Object.prototype.toString.call(<variable/object>);

Example

let myVar: any = "Hello, World!";

if (Object.prototype.toString.call(myVar) === "[object String]") {
  console.log("myVar is a string");
} else {
  console.log("myVar is not a string");
}

Output

myVar is a string object

That’s it!

Related posts

How to Check if an Object is Empty in TypeScript

How to Check If Object is an Array in TypeScript

Leave a Comment