Primitive Types
In TypeScript, you annotate variables utilizing a colon syntax : type right after the variable name.
The Core Primitives
// Number (Floats and Ints share the same type)
let price: number = 29.99;
let count: number = 100;
// String
let username: string = "Alice";
// Boolean
let isStudent: boolean = true;
If you try to reassign one of these variables to a non-matching data type, the compiler will instantly throw an error.
let score: number = 85;
// TS Error: Type 'string' is not assignable to type 'number'.
score = "Eighty-Five";
Type Inference
TypeScript is incredibly smart. You do not need to explicitly state the type if you assign a value immediately upon creation. TS will "infer" the type natively.
// TS automatically infers that this is a Boolean!
let isOnline = false;
// TS Error: Type 'number' is not assignable to type 'boolean'.
isOnline = 15;
Should you rely on Inference? Yes! For simple primitives, relying on inference keeps your code looking much cleaner. You generally only need explicit
:type syntax if you are declaring a variable without assigning its value instantly.