TypeScript Tutorial

Type Annotations

Explicit types for strings, numbers, booleans, and arrays

What are Type Annotations?

In TypeScript, a Type Annotation is the syntax you use to tell the compiler exactly what "type" of data a variable is allowed to hold. You add it after the variable name using a colon (:).
typescript
// Explicit type!
let name: string = "Alpha";
let count: number = 10;
let isReady: boolean = true;

Primitives: String, Number, Boolean

These correspond to JavaScript's primitive types. Unlike in Java, types in TypeScript are lowercase.
TypeExamplesDescription
string"Hi", 'A', ```Text
number10, -1.5, 0xffALL numbers (int, float, hex)
booleantrue, falseLogic
typescript
let age: number = 25;
let username: string = "admin";
let isActive: boolean = false;

Array Annotations

Wait! There are two different ways to annotate an array in TypeScript. Both do the exactly same thing; it's a matter of preference.
  1. Type[]: The most common and concise way.
  2. Array<Type>: The generic syntax (Uses the "angle-bracket" style).
typescript
// Any list of numbers!
let scores: number[] = [80, 90, 75];

// A generic list of strings!
let names: Array<string> = ["Alpha", "Beta"];

Function Annotations

You should also annotate the Parameters and the Return Type of your functions.
typescript
// Function takes a string; returns nothing (void)!
function logMessage(msg: string): void {
  console.log("Log: " + msg);
}

// Function takes two numbers; returns a number!
const add = (a: number, b: number): number => {
  return a + b;
};

Summary

TypeExamplesDescription
string"Hello!"Textual data
number42, 3.14Any numerical value
booleantrue, falseLogical true or false
number[][1, 2, 3]A list of numbers
voidfunction(): voidReturns nothing!
anylet x: any = 1;The "Escape Hatch" (AVOID THIS!)
Best ForVariable declaration, function inputs/outputs
ExplicitManually specifying the type (: type)
ImplicitTypeScript guesses the type! (See Type Inference!)
AnnotateUse types to "document" your code while writing it
SafePrevents assigning the wrong data to a variable
CleanYour IDE will provide better suggestions with types
ModernThe standard way to write safe JavaScript
NullTypes can also be null or undefined (If allowed!)
Neverfunction(): never (For code that NEVER returns!)
ObjectYou can also annotate objects! (See Objects/Interfaces)
Tuples[number, string] (An array with fixed types and size!)
InferenceTypeScript is very smart; usually it knows the type!
Compilertsc checks these annotations before building
RuntimeAnnotations are REMOVED when your code is transpiled to JS
IdentityAn object never "forgets" its real type internally
MultipleUse "Union Types" to allow 2+ types (`stringnumber`)
BigIntlet x: bigint = 100n; (For massive numbers!)
Symbollet x: symbol = Symbol(); (Unique identifiers!)
UnknownA safer alternative to any (Requires type checking!)
ReadOnlyreadonly number[] (A list that CANNOT be modified!)