Check if a Variable Is a String in TypeScript

Migel Hewage Nimesha Jan 30, 2023 Jul 04, 2022
  1. TypeScript Types
  2. Use the typeof Operator to Check if a Variable Is a String in TypeScript
  3. Use the instanceof Operator to Check if a Variable Is a String in TypeScript
  4. Use Object.prototype to Check if a Variable Is a String in TypeScript
Check if a Variable Is a String in TypeScript

This article will discuss checking if a variable is a string in TypeScript.

TypeScript Types

TypeScript is a superset of the JavaScript language where the type checking is taken place at compile time. Whenever a variable, function, or argument is declared, TypeScript allows us to assign the types explicitly, which assists in identifying the errors in advance.

// variable declaration and assignment
let stringTypeVariable: string = 'Hello world';
let booleanTypeVariable: boolean = true;
let numberTypeVariable: number = 10;

// function declaration
function calculateSum(numOne: number, numTwo: number): number {
    return numOne + numTwo;
}

the string Type in TypeScript

TypeScript string type holds a collection of characters. It is a primitive data type where a sequence of characters is wrapped between single or double quotation marks.

The text data can be stored in the string type. There are two ways that you can store strings in TypeScript:

  1. Store as a primitive type
  2. Store as an object instance

Store String as a Primitive Type

Usually, the primitive string type holds the string literals. The primitive strings are recommended over object instances.

let stringTypeName: string = 'John Doe';
let stringTypeId: string = "User001";

Store String as an Object Instance

TypeScript supports String object instances where it wraps the primitive string type with additional helper methods. The String object instance will have the String.prototype in its prototype chain.

let stringVal: String = new String('This is a String object');
let anotherStrVal: String = String('Another String object');

There are a few ways to check whether a given variable holds a string or not. Usually, the typeof operator is used to check the primitive string types, and the instanceof operator can be used with String object instances.

Other than that, the Object.prototype property can be used to check whether the given type is a string or not.

Use the typeof Operator to Check if a Variable Is a String in TypeScript

The typeof is a TypeScript unary operator that returns the data type of the specified operand.

Syntax:

typeof <operand>

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

Let’s create a primitive string, userName.

let userName: string = 'Ricky hardy';

Next, we will be using the typeof operator to check the data type of the userName variable. Let’s print it to the console as shown in the following:

console.log(typeof userName);

Output:

string

Hence, the typeof operator can be used to check for the primitive type strings within a conditional code fragment, as shown in the following:

if (typeof userName === 'string') {
    // logic to be executed when the type is a string
} else {
    // logic to be executed for non-string types
}

Use the instanceof Operator to Check if a Variable Is a String in TypeScript

The instanceof operator operates on the prototype chain of a given object and checks whether the prototype property appeared there. It checks whether the specified object is a child or an instance of a given constructor.

Syntax:

<object> instanceof <constructor/type>

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

Let’s instantiate a new String object, vehicleBrand.

let vehicleBrand: String = new String("AUDI");

Next, we will utilize the instanceof operator to check whether the vehicleBrand is a string type.

console.log(vehicleBrand instanceof String);

Output:

true

As expected, the operator returns true because the vehicleBrand is a String object.

Use Object.prototype to Check if a Variable Is a String in TypeScript

The Object.prototype can also be used as a more generic way of identifying string types in TypeScript. This property contains the toString() method, where we can use the call method and check for the type of a specified variable’s prototype.

Syntax:

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

This should return a string in the following format:

"[object String]"
OR
"[object Array]"
OR
.
.
.

Let’s create a new variable, newStringValue.

let newStringValue: string = 'This is a new string';

Next, we will be checking the newStringValue variables constructor type using the Object.prototype property.

console.log(Object.prototype.toString.call(newStringValue));

Output:

[object String]

As expected, the type is a string.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - TypeScript String