Basic Types: Numbers, Strings, and Booleans

Explore the fundamental data types in TypeScript: number, string, and boolean. Learn how to declare and use them effectively.


TypeScript Basics: Numbers, Strings, and Booleans

Welcome to a beginner's guide to the fundamental data types in TypeScript: number, string, and boolean. Understanding these types is crucial for writing well-typed and maintainable TypeScript code.

Basic Types: Numbers, Strings, and Booleans

TypeScript, like JavaScript, has a set of basic data types used to represent different kinds of values. Let's explore the core types:

Number

The number type represents numeric values, including integers and floating-point numbers. TypeScript, unlike some other languages, doesn't differentiate between integers and floating-point numbers; it uses the number type for all of them.

 let age: number = 30;
let price: number = 19.99;
let largeNumber: number = 1234567890;
let negativeNumber: number = -5;

console.log("Age:", age); // Output: Age: 30
console.log("Price:", price); // Output: Price: 19.99
console.log("Large Number:", largeNumber); // Output: Large Number: 1234567890
console.log("Negative Number:", negativeNumber); // Output: Negative Number: -5 

String

The string type represents textual data. You can use single quotes ('), double quotes ("), or backticks (`) to define strings.

 let firstName: string = "John";
let lastName: string = 'Doe';
let message: string = `Hello, ${firstName} ${lastName}!`; // Template literals

console.log("First Name:", firstName); // Output: First Name: John
console.log("Last Name:", lastName); // Output: Last Name: Doe
console.log("Message:", message); // Output: Message: Hello, John Doe! 

Using backticks allows you to create template literals, which can embed expressions directly within the string using the ${...} syntax.

Boolean

The boolean type represents a logical value, which can be either true or false.

 let isAdult: boolean = true;
let isStudent: boolean = false;

console.log("Is Adult:", isAdult); // Output: Is Adult: true
console.log("Is Student:", isStudent); // Output: Is Student: false 

Declaring and Using Types Effectively

TypeScript's type system provides significant benefits by catching potential errors during development. Explicitly annotating your variables with types (e.g., let age: number) allows the TypeScript compiler to verify that you are using the variable correctly. If you try to assign a value of the wrong type, the compiler will issue an error.

 // Example of a type error
let count: number = "10"; // This will cause a TypeScript error: Type 'string' is not assignable to type 'number'. 

While TypeScript can often infer the type of a variable based on its initial value (type inference), explicitly declaring the type is generally considered good practice, especially for more complex code or when working in a team. It makes your code more readable and helps prevent errors.