It is understood that JavaScript lacks a type system, meaning we cannot define a variable's type, such as number, string, or Boolean, within JavaScript. Conversely, TypeScript allows for the specification of types for variables, function arguments, and properties of objects, as it is a typed language.
Type Annotations are markers that can be applied at any point where a type is utilized. While their use is not compulsory in TypeScript, Type Annotations assist the compiler in verifying variable types and preventing mistakes related to data types.
The type can be indicated by placing a colon (: Type) following a variable name, parameter, or property. It is permissible to include a space between the colon and the variable name, parameter, or property. TypeScript encompasses all primitive data types found in JavaScript, including number, string, Boolean, and others.
Syntax
var variableName: TypeAnnotation = value;
The subsequent example illustrates type annotations applied to variables featuring various data types.
var age: number = 44; // number variable
var name: string = "Rahul"; // string variable
var isUpdated: boolean = true; // Boolean variable
In the preceding example, variables are defined alongside their respective data types. These instances illustrate the concept of type annotations. In this context, it is not permissible to alter the value using an alternate data type that differs from the designated type. Attempting to do so will result in an error from the TypeScript compiler. For instance, if a string is assigned to a variable named age or a number to the variable name, a compilation error will occur.
Use of Type Annotation as a parameter
The following example illustrates the use of type annotations with parameters.
Example
function display(id:number, name:string)
{
console.log("Id = " + id + ", Name = " + name);
}
display(101, "Rohit Sharma");
Output:
Id = 101, Name = Rohit Sharma
Inline Type Annotation
In TypeScript, inline type annotations enable the definition of an object for every property within the object.
Syntax
:{ /*Structure*/ }
Example
var student : {
id: number;
name: string;
};
student = {
id: 100,
name : "John"
}
In this instance, we create an object named student that includes two attributes: "id" and "name," which are designated with the data types number and string, accordingly. If we attempt to assign a string value to the id property, the TypeScript compiler will generate an error indicating that the property types are incompatible.