TypeScript Tutorial in Hindi #31 typeGurad | typeof, instanceof, and custom type guards

TypeGuard In TypeScript

A Type Guard in TypeScript is a technique used to narrow down the type of a variable within a conditional block


Types of TypeGuard

typeof

instanceof

Custom Type


Why use TypeGaurd ?


Provides better type safety

Apply conditions with data type

Helps TypeScript infer types automatically


keys of TypeScript?


What is keyof?

Example

How to use object keys with keyof

Interview Questions


typeGuard.ts

let userData20: number | string | boolean = "Anil sidhu"

// userData20=true
// if(typeof userData20 =="boolean"){
// console.log('this is a bool data type');

// }
// else if(typeof userData20 =="string"){
// userData20
// console.log('this is a string data type');

// }else{
// console.log("this is a number");

// }

// function checkDataType(data:string | number){

// if(typeof data =='number'){
// console.log("this is a number");

// }else{

// console.log("this is a string");
// }

// }

// checkDataType('anil')



class Product21 {

}

var p1 = new Product21()
class Order21 {

}

var o1 = new Order21();


// function checkDetails(data :Order21 |Product21 ){
// if(data instanceof Order21){
// console.log('this is a order');

// }else{

// console.log('this is a product');
// }
// }

// checkDetails(o1);


interface userData {
name: string,
city: string

}
interface userInfo {
id: number,
email: string
}
var userData22: userData | userInfo
userData22 = {
name: 'anil sidhu',
city: 'gurgaon'
}


var userData21: userData | userInfo = {
id: 100,
email: 'anil@test.com'
}
function checkUserInfo(data: userData | userInfo) {
if ((data as userData).name != undefined) {
console.log('this is a user data');

} else {
console.log('this is a user info');

}
}
checkUserInfo(userData22)


typeGuard.js

"use strict";
let userData20 = "Anil sidhu";
// userData20=true
// if(typeof userData20 =="boolean"){
// console.log('this is a bool data type');
// }
// else if(typeof userData20 =="string"){
// userData20
// console.log('this is a string data type');
// }else{
// console.log("this is a number");
// }
// function checkDataType(data:string | number){
// if(typeof data =='number'){
// console.log("this is a number");
// }else{
// console.log("this is a string");
// }
// }
// checkDataType('anil')
class Product21 {
}
var p1 = new Product21();
class Order21 {
}
var o1 = new Order21();
var userData22;
userData22 = {
name: 'anil sidhu',
city: 'gurgaon'
};
var userData21 = {
id: 100,
email: 'anil@test.com'
};
function checkUserInfo(data) {
if (data.name != undefined) {
console.log('this is a user data');
}
else {
console.log('this is a user info');
}
}
checkUserInfo(userData22);