Skip to content
-
Type Assertions and Guards
Last Updated :
23 Jul, 2025
Type Assertions and Type Guards are powerful features in TypeScript that are used to handle data types more effectively. They allow you to narrow down types, assign the correct types, and safely access properties or methods that may not be directly accessible based on the type.
What are Type Assertions?
Type Assertions allow you to explicitly define a type when TypeScript cannot infer it automatically. They do not change the actual data but instruct TypeScript to treat a value as a specific type.
Syntax for Type Assertions
There are two ways to write type assertions in TypeScript:
1. Using the as
keyword (Recommended)
JavaScript
let value: any = "Hello, TypeScript";
let strLength: number = (value as string).length;
console.log(strLength); // Output: 16
In this Example
- value as string tells TypeScript to treat value as a string.
- .length is accessed safely after the assertion.
2. Using the angle-bracket (<>
) syntax (not recommended in JSX files)
JavaScript
let value: unknown = "Hello, TypeScript";
let strLength: number = (<string>value).length;
console.log(strLength); // Output: 17
In this example
- <string>value asserts value as a string.
- .length retrieves the number of characters in "Hello, TypeScript" (17).
When to Use Type Assertions
- When you have more specific knowledge about the type: If you know the type of a variable better than TypeScript does, you can assert the type to make it work as expected.
- In cases of dynamic content: For example, when you work with DOM elements or data that is fetched from external sources (such as JSON), where the type might not be inferred by TypeScript.
Note: Type Assertions do not perform type conversion; they only tell TypeScript to treat a value as a specific type.
Type Guards
Type Guards are techniques used to check and refine types at runtime, ensuring safe operations based on the variable’s actual type.
1. typeof Type Guard (For Primitives)
The typeof operator helps check primitive types like string, number, or boolean.
JavaScript
function example(value: number | string): void {
if (typeof value === "string") {
console.log(value.length); // Safe to access length
} else {
console.log(value.toFixed(2)); // Safe for number
}
}
example("Hello, TypeScript!"); // Output: 17
example(123.456); // Output: 123.46
Output
17
123.46
In this example
- If value is a string, we access .length.
- If value is a number, .toFixed(2) is used.
2. instanceof Type Guard (For Objects and Classes)
The instanceof operator checks if an object belongs to a specific class.
JavaScript
class Animal {
move() {
console.log("Moving...");
}
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
function makeSound(animal: Animal) {
if (animal instanceof Dog) {
animal.bark(); // Safe to call bark()
} else {
animal.move(); // Safe to call move()
}
}
const dog = new Dog();
makeSound(dog);
const animal = new Animal();
makeSound(animal);
Output
Woof!
Moving...
In this example
- instanceof ensures animal is a Dog before calling bark().
- If not, it falls back to the move() method from Animal.
3. User-Defined Type Guards
Custom functions can act as type guards for complex types.
JavaScript
interface Cat {
type: "cat";
meow(): void;
}
interface Dog {
type: "dog";
bark(): void;
}
function isCat(animal: Cat | Dog): animal is Cat {
return animal.type === "cat";
}
function makeSound(animal: Cat | Dog) {
if (isCat(animal)) {
animal.meow();
} else {
animal.bark();
}
}
const myCat: Cat = { type: "cat", meow: () => console.log("Meow!") };
makeSound(myCat);
Output
Meow
In this example
- isCat() ensures animal is a Cat before calling meow().
- If not, it calls bark() safely.
Why Use Type Guards?
- Improved Type Safety: Type Guards allow TypeScript to narrow down the type within a specific scope, ensuring that operations on variables are type-safe and reducing runtime errors.
- Handling Union Types: When working with union types (e.g., string | number), Type Guards help determine the exact type at runtime, so you can handle each type appropriately.
Differences Between Type Assertions and Type Guards
Feature | Type Assertions | Type Guards |
---|
Type Safety | No runtime check, can be unsafe | Performs runtime checks |
Syntax | Uses as or < > syntax | Uses typeof , instanceof , in , or custom predicates |
Use Case | When you know the type beforehand | When dealing with multiple possible types |
Similar Reads
Angular Authentication Using Route Guards In Angular, implementing authentication is important for securing routes and controlling access to different parts of the application based on user authentication status. Angular provides a powerful feature called Route Guards, and among them, the Auth Guard is used to control navigation based on th
12 min read
Auth Guards in Angular 9/10/11 AuthGuard is used to protect the routes from unauthorized access in angular. How AuthGuard Works? Auth guard provide lifecycle event called canActivate. The canActivate is like a constructor. It will be called before accessing the routes. The canActivate has to return true to access the page. If it
3 min read
Recursive Type Guards In TypeScript In TypeScript type guards help determine the type of a variable at runtime, they are especially useful when dealing with complex types like unions, discriminated unions or even recursive structures and a recursive type guard is a type guard function that can handle complex nested types, including th
6 min read
Guard Clause in JavaScript In JavaScript, a Guard Clause is a programming pattern that uses conditional statements at the beginning of a function to check for specific conditions. When these conditions are met, the function returns early, preventing the rest of the code from executing. Guard Clauses enhance code readability a
2 min read
How to use AuthGuard For Angular 17 routes? In Angular applications, it is often necessary to protect certain routes to prevent unauthorized access. The Angular Router provides a feature called Route Guards, which allows you to control access to routes based on specific conditions. One of the commonly used Route Guards is AuthGuard, which che
6 min read
Guards in NestJS NestJS is an extensible framework for building server-side applications using TypeScript. One of its key features is the ability to implement guards, which provide a way to intercept and control the flow of incoming requests to routes. Guards are used to implement authorization logic, ensuring that
2 min read
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}