How to Check Types in Typescript?
Last Updated :
07 Aug, 2024
Checking types in TypeScript involves methods like typeof for primitive types, instanceof for class instances, and custom type guards for complex type validation. These techniques help ensure variables are correctly typed, improving code safety, and readability, and preventing runtime errors.Here are several approaches to check types in TypeScript:
1. Using the typeof operator
The typeof operator is a straightforward way to determine the data type of a value. It returns a string representing the type, such as "string," "number," or "boolean."
Example: Checking Types with typeof
In this code snippet, we demonstrate how to check the types of variables num and str using the typeof operator in TypeScript.
TypeScript
let num: number = 42;
let str: string = "Hello, TypeScript";
if (typeof num === "number") {
console.log("num is a number");
}
if (typeof str === "string") {
console.log("str is a string");
}
Output:
num is a number
str is a string
2. Using the instanceof Operator
The instanceof operator in TypeScript verifies if an object inherits from a specific class, allowing you to check object lineage. This is valuable for working with custom classes.
Example: Checking Instances with instanceof
In this example, we define a Person class with name and age properties. We create an instance of Person called person1 and use the instanceof operator to check if person1 is an instance of the Person class. If it is, it logs a message confirming it.
TypeScript
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let person1 = new Person("Alice", 30);
if (person1 instanceof Person) {
console.log("person1 is an instance of Person");
}
Output:
person1 is an instance of Person
3. Using Type Guards
Type guards are excellent characteristics that help restrict a variable's type according to specific conditions. They improve code readability and enable complex type checks.
Example: Using Type Guards
In this example, we define a type guard function isString that checks if the provided value is a string. We then use this function to conditionally check if unknownValue is a string, and if it is, we safely utilize string methods like toUpperCase().
TypeScript
function isString(value: any): value is string {
return typeof value === "string";
}
let unknownValue: any = "HELLO";
if (isString(unknownValue)) {
console.log("unknownValue is a string:", unknownValue.toUpperCase());
}
Output:
unknownValue is a string: HELLO
FAQs - How to Check Types in Typescript?
What is the typeof operator used for in TypeScript?
The typeof operator is used to determine the data type of a value, returning a string such as "string," "number," or "boolean."
How does the instanceof operator work in TypeScript?
The instanceof operator checks if an object is an instance of a specific class, verifying object inheritance.
What are type guards in TypeScript?
Type guards are functions or conditions that help narrow down the type of a variable within a certain scope, enhancing type safety and code readability.
Can you use typeof to check for custom class instances?
No, typeof cannot check for custom class instances. For this, you should use the instanceof operator.
Why are type guards important in TypeScript?
Type guards are important because they provide a way to perform complex type checks and ensure that a variable conforms to a specific type within a given scope, thereby preventing runtime errors.
Similar Reads
How to check interface type in TypeScript ?
Typescript is a pure object-oriented programming language that consists of classes, interfaces, inheritance, etc. It is strict and it statically typed like Java. Interfaces are used to define contacts in typescript. In general, it defines the specifications of an entity. Below is an example of an in
2 min read
How to Check the Type of an Object in Typescript ?
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using
3 min read
How To Get Types From Arrays in TypeScript?
In TypeScript, arrays are a common data structure, but sometimes it's necessary to extract the types of elements stored in an array for type-checking or validation purposes. TypeScript provides several ways to extract types from arrays, enabling more type-safe operations. We will explore different m
4 min read
How to use Type Guards in TypeScript ?
Here are the methods to use type guards in TypeScript: 1. Using typeof Type GuardsThe typeof operator checks the type of a variable, primarily for primitive types like string, number, boolean, etc. [GFGTABS] JavaScript function processValue(value: string | number) { if (typeof value === 'string
3 min read
How to declare nullable type in TypeScript ?
In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
2 min read
How to Get a Variable Type in TypeScript
Understanding how to effectively ascertain the type of a variable in TypeScript is important for maintaining type safety and ensuring code robustness. In this article, we'll explore various approaches to determine the type of a variable, ranging from basic JavaScript operators to TypeScript-specific
2 min read
How to create conditional types in TypeScript ?
Conditional types in TypeScript enable defining types based on conditions, similar to conditional statements in code. They determine different types of values, making functions adaptable to various input types, and enhancing code flexibility and maintainability. Syntax: We can create conditional typ
3 min read
How to Use Partial Types in TypeScript ?
Partial types in TypeScript offer a versatile solution for creating new types with a subset of properties from existing types. This feature proves invaluable in scenarios where you need to work with incomplete data structures or define flexible interfaces. Below are the approaches to using partial t
2 min read
TypeScript Conditional Types
In TypeScript, conditional types enable developers to create types that depend on a condition, allowing for more dynamic and flexible type definitions. They follow the syntax T extends U ? X : Y, meaning if type T is assignable to type U, the type resolves to X; otherwise, it resolves to Y.Condition
4 min read
TypeScript Object Types
TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters. Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
3 min read