In this blog, we’ll see a how to assign type annotations to types to variables and functions of Typescript
Type annotation in typescript?
Type annotations are used in TypeScript to clearly indicate the types of identifiers such as variables, functions, objects, and so on.
Assigning annotation types to variables :
We can provide variables types using type annotations in TypeScript.
Before every assignment, place a colon after the variable name and then the type to create a type annotation.
Syntax:
Assigning annotation types to Functions
We know that type annotation allows us to explicitly specify the type of variables, functions, and other objects. Let’s look at the typescript annotating function’s syntax
Syntax:
//Addition
function add(a: number, b: number) {
return a + b;
}
//Subraction
function Minus(a: number, b: number) {
return a – b;
}
//multiply
const multiply = (a: number, b: number): number => a * b;
function Multiply(a: number, b: number) {
return a * b;
}
Typescript type annotation for object
The most typical type in typescript is called a “object type.” This applies to any JavaScript value that has properties, which is practically every single one of them! List the properties of an object type together with their types to define it.
Example:
function Student(obj: { A: string; B: string }) {
console.log(“The Student A name is ” + obj.A);
console.log(“The Student B name is ” + obj.B);
}
employee({ A: “Kcdc”, B: “Jjc” });
Advantages Of Using Type Annotations In Typescript
- Type annotations are very useful to explicitly specify the type of variables, function, and more.
- Using type annotation makes the code more readable and easier to understand.
- Type annotations help the compiler in checking types and help avoid errors dealing with data types.
- With the help of type annotations we can declare the types of function parameters and also the return type of functions.