Basic Types
In TypeScript, the basic types include
The
boolean
, number
, string
, array
, tuple
, and enum
. These types are built into the language and can be used to specify the type of a variable or a function parameter or return value.The
boolean
type represents a logical value, either true
or false
. It is commonly used in conditional statements to control the flow of a program. For example:let isHappy: boolean = true;
if (isHappy) {
console.log("I'm feeling great!");
} else {
console.log("I'm not so happy right now.");
}
The
number
type represents a numeric value. This can be an integer, a floating-point value, or other numeric types supported by JavaScript. For example:let score: number = 100;
console.log(`Your score is ${score}`);
The
string
type represents a sequence of characters, such as a word or a phrase. Strings are enclosed in quotation marks (either single or double) and can be concatenated using the +
operator. For example:let name: string = "Alice";
let message: string = "Hello, " + name + "!";
console.log(message); // outputs "Hello, Alice!"
The
array
type represents an ordered collection of values. The type of the values in the array must be specified using a type parameter. For example:let numbers: number[] = [1, 2, 3, 4, 5];
console.log(numbers); // outputs [1, 2, 3, 4, 5]
The
tuple
type represents a fixed-length array, where the type of each element is known but does not have to be the same. For example:let user: [string, number] = ["Alice", 25];
console.log(`${user[0]} is ${user[1]} years old.`); // outputs "Alice is 25 years old."
The
enum
type is a way to give more friendly names to sets of numeric values. For example:enum Color {Red, Green, Blue};
let favoriteColor: Color = Color.Green;
console.log(`My favorite color is ${favoriteColor}.`); // outputs "My favorite color is Green."
Overall, the basic types in TypeScript provide a way to specify the type of a variable or function parameter or return value, which can help catch errors and make your code more readable and maintainable.