A type guard is a cool TypeScript technique that allows you to check the type of a variable within a conditional block.
It is often used to determine the type of an argument within a function body and then make a decision based on that type.
what is Typescript
Javascript, Java, Python, PHP, and C are all programming languages but Typescript is a superset of JavaScript. It is a typed superset of JavaScript. Typescript is a new programming language created and maintained by Microsoft.
It is a type-safe and object-oriented programming language. It is a superset of JavaScript. It can also be considered as a typed superset of JavaScript. A typed superset of JavaScript, TypeScript compiles to standard JavaScript. TypeScript adds optional static types, classes, and modules to JavaScript.
how to install typescript?
Step 1: Download NPM from their official website at npmjs.
Step 2: Open the terminal or Node command prompt.
Step 3: Give the following command to download TypeScript and typescript globally.
npm install -g typescript
Step 4: Now create a directory and change the directory it.
mkdir myapp && cd myapp
Step 5: Now type "tsc -init" in windows or "tsc -init -n hello" in mac to create a js file and then type "npm install angular2" to install angular2 in the directory.
Step 6: Type "tsc" in windows or "tsc -w" in mac to compile the typescript file.
Step 7: Open the folder in your browser and you will see the compiled application if you have reached here you have successfully installed typescript.
It is a guard instance
A built-in type guard called instanceof can be used to determine whether a value is an instance of a particular function Object() { [native code] } function or class. To ascertain the type of an instance type, we can use this type guard to test whether an object or value is derived from a class.
Below is the instanceof type guard's basic syntax.
example of a guard:
interface Accessory {
brand: string;
}
class Necklace implements Accessory {
kind: string;
brand: string;
constructor(brand: string, kind: string) {
this.brand = brand;
this.kind = kind;
}
}
class bracelet implements Accessory {
brand: string;
year: number;
constructor(brand: string, year: number) {
this.brand = brand;
this.year = year;
}
}
const getRandomAccessory = () => {
return Math.random() < 0.5 ?
new bracelet('cartier', 2021) :
new Necklace('choker', 'TASAKI');
}
let Accessory = getRandomAccessory();
if (Accessory instanceof bracelet) {
console.log(Accessory.year);
}
if (Accessory instanceof Necklace) {
console.log(Accessory.brand);
}
What is type casting in TypeScript?
let string1: string
string1 = as < string >
string1 = string1
string1 = undefined
string1 = null
string1 = undefined
the as keyword is used for typecasting
let input = document.querySelector('input["type="text"]');
console.log(input.value);
let input = document.querySelector('input[type="text"]') as HTMLInputElement;
console.log(input.value);
0 Comments