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 typeof Operator
  3. Using instanceof Operator
  4. Using Object.prototype.toString()

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.

Here is a code 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 is “used to check the type of a variable at runtime.” If a variable is a string, typeof will return the string “string”.

Here is a code 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 a constructor’s prototype property appears anywhere in an object’s prototype chain. 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”.

Here is a code 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.

Here is a code 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 an Object is an Array in TypeScript