TypeScript is a statically typed programming language that builds on JavaScript by adding optional static typing. One of the core features of TypeScript is its type system, which helps developers write more reliable and maintainable code by catching errors at compile time rather than runtime.
In this tutorial, we'll explore the basic data types available in TypeScript: number, string, and boolean. Understanding these fundamental types will provide a solid foundation for working with TypeScript.
The number type represents numeric values. In JavaScript (and therefore TypeScript), numbers are always floating-point values. This means that integers and decimals are both represented by the same type.
Here are some examples of using the number type:
1let age: number = 25;2let height: number = 5.9;3let pi: number = 3.14159;45console.log(age); // Output: 256console.log(height); // Output: 5.97console.log(pi); // Output: 3.14159
The string type represents textual data. Strings can be defined using either single quotes (') or double quotes (").
Here are some examples of using the string type:
1let name: string = "Alice";2let greeting: string = 'Hello, World!';3let message: string = `The value of pi is ${pi}`;45console.log(name); // Output: Alice6console.log(greeting); // Output: Hello, World!7console.log(message); // Output: The value of pi is 3.14159
The boolean type represents a logical entity and can have only two values: true or false. It is often used in conditional statements.
Here are some examples of using the boolean type:
1let isStudent: boolean = true;2let hasGraduated: boolean = false;34console.log(isStudent); // Output: true5console.log(hasGraduated); // Output: false
In the next section, we will delve into more complex data structures in TypeScript, starting with Arrays in TypeScript. Understanding how to work with arrays is crucial for handling collections of data efficiently.
Stay tuned!