5 common ways of Type Annotation in TypeScript

What is Type Annotation?

TypeScript is a statically-typed language. Hence, Type Annotation is an essential part of TypeScript that you need to be well familiar with. Type Annotations mean different ways that you can define types of variables, parameters, and return values of functions, and properties (of objects).

There are many ways to do type annotation in TypeScript. Some are more common than others. We are going to discuss the most common ways of type annotation.

Explicit type annotation 

This is probably the most common way to do it. Let’s see how to use explicit annotation on variables using some of the primitive data types in TypesScript.

let firstName: string = "John";
let age :number = 32;
var isPrimeNumber : boolean = false;
const COUNTRY : string = "United States";


Note: You can also define type by inference.

Interfaces for type annotation 

Interfaces are another way of doing type annotations. Interfaces can be used to declare object types as follows.

interface Person {
    firstName : string;
    age : number;
}

//Then you can use the Person object type to define a variable as follows. 
let friend: Person =  { firstName: 'john', age:70 }

Type aliases for type annotation 

Type Aliases let you have a custom name for a type. Let’s see how to work with type aliases.

type mystring = string;
let country:mystring = "USA";

You can also alias object types

type Student = {
    firstName: string,
    age: number
}

// now , you can use the alias 'Student' to create object of that type
let californiaStudents: Student = { firstName:'john', age: 23 };

You can do the above code as follows if you use an interface to declare an Object type.

interface Person{
    firstName : string;
    age : number;
}

type Student = Person;
let californiaStudents: Student = { firstName:'john', age: 33 };

TypeScript Generics

Generics in Typescript allows you to define functions, classes, and type aliases that can work with multiple types. You can use generics declare generics type aliases as below. Let’s how to use Generics with functions( generic functions ).

function myFunction<anyType>( para :anyType ) : anyType{
    return para;
}

In TypeScript, the syntax for the Generics type <name>. Here the ‘name’ can be any variable name you want. In the above example, it is <anyType>. This special variable, unlike any other variables, does not hold values, but types.

Therefore, the above function is a generic function that can work with multiple types. Let’s now see how you can call this function so that you will better understand how it works with multiple types.

There are two ways you can call the above function

myFunction<string>(“john”); //recommended way of calling generic functions 
myFunction(“john”)//another way

In the above function calls, I have passed “string” as the type. If you assign an incompatible value (such as 123 ), it will produce an error: Argument of type ‘string’ is not assignable to parameter of type ‘number’.

You can call the generic function with any other type and compatible value.

myFunction<number>( 123 ); or myFunction(123 )

You can even pass Object types.

interface myObj{
    name:string,
    age:number
}

myFunction<myObj>({ name:"john", age: 77 }) or 
myFunction({ name:"john", age: 77 });

You can also create Generics for Type aliases.

type Code<anyType> = anyType;
let countryCode: Code<number> = 1 or let countryCode: Code<string> = "Asia_In";

You can also create Generics for classes. I will be discussing this topic in a future post.

Union Types

Another common way of annotating is using Union types.  Union allows you to define variables that can hold different types of values. How do you achieve it? By combining two or more other data types as follows.

let studentNum : string | number;
Now you can assign either strings or numbers as a student number. 
studentNum = 1; or studentNum = "stu_1"

Union types can also be used in functions as parameters or/and return types. The following example uses union type in parameters.

function getStudentNum( studentNum:( string | number )){   
    return studentNum;
}

getStudentNum( "001" )//calling the function passing a string
getStudentNum(1);// calling the function passing a number

Type by Inference

In the above 5 different ways of a type annotation, we explicitly mentioned the type of the variable. While this is a good programming practice, TypeScrpt also can determine the type of a variable by inference. That is by looking at the value assigned to the variable, Typescript can infer the type of the variable.

let myString = "Hello World";

myString = 5; //a compiler error: Type 'number' is not assignable to type 'string'

Conclusion

Type annotations are commonly done in TypeScript using the above methods. However, this is not an exclusive list. There are other less common ways to do type annotation. If you are a beginner, this is your starting point, and then you can gradually expand your knowledge. Additionally, the knowledge of Typescript basic types is helpful when you study Type annotations.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top