Understanding TypeScript Basic Types and Variables
A beginner-friendly guide to TypeScript basic types and variable declarations.
TypeScript is a powerful language that builds on JavaScript by adding static types. This means you can define what type of data a variable can hold, helping you catch errors before running your code.
In TypeScript, you declare variables and specify their types using syntax like `let name: string = 'Alice';`. The most common basic types are `string`, `number`, `boolean`, `any`, and `void`. Let's explore how these work.
let userName: string = 'Alice';
let userAge: number = 25;
let isMember: boolean = true;
// The 'any' type allows any value, but using it removes type safety
let flexibleValue: any = 42;
flexibleValue = 'Now a string';
// 'void' is used mostly for functions that do not return a value
function logMessage(message: string): void {
console.log(message);
}If you try to assign a value that doesn’t match the declared type, TypeScript will show an error. For example, `let userName: string = 123;` causes an error because `123` is a number, not a string. This helps you avoid bugs by enforcing consistent types.