Welcome back to our TypeScript series! Today, we'll explore the basic types that TypeScript offers, which are essential for writing safer and more predictable code.
1. Primitive Types
TypeScript includes several primitive data types that you'll use frequently in your code.
String
The string
type is used for textual data. You can use single quotes (' '
), double quotes (" "
), or backticks (``
) for template literals.
let firstName: string = "John";
let greeting: string = `Hello, ${firstName}!`;
Number
The number
type in TypeScript represents both integer and floating-point numbers. TypeScript supports decimal, hexadecimal, octal, and binary literals.
let age: number = 30;
let hex: number = 0xff;
let binary: number = 0b1010;
let octal: number = 0o744;
Boolean
The boolean
type has only two values: true
and false
.
let isDone: boolean = false;
2. Arrays and Tuples
Array
An array
type can hold multiple values of the same type. You can define arrays using the type followed by square brackets ([]
) or the generic array type Array<type>
.
let scores: number[] = [90, 85, 80];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
Tuple
A tuple
type allows you to define an array with a fixed number of elements where each element can have a different type.
let person: [string, number] = ["Alice", 25];
3. Enums
Enums are a way to define a set of named constants. They can make your code more readable and easier to maintain.
enum Color {
Red,
Green,
Blue
}
let backgroundColor: Color = Color.Green;
You can also assign specific values to enum members.
enum Status {
Active = 1,
Inactive = 0,
Pending = -1
}
let currentStatus: Status = Status.Active;
4. Special Types
Any
The any
type allows you to assign any type of value to a variable. It is useful when the type of data is not known at the time of writing the code. However, use it sparingly as it defeats the purpose of TypeScript’s type checking.
let anything: any = "Hello";
anything = 25;
anything = true;
Unknown
The unknown
type is similar to any
, but it’s safer because you need to perform a type check before performing operations on it.
let maybe: unknown = 10;
if (typeof maybe === "number") {
let num: number = maybe;
}
Void
The void
type is typically used for functions that do not return a value.
function logMessage(message: string): void {
console.log(message);
}
Null and Undefined
null
and undefined
are their own types in TypeScript. They are subtypes of all other types, meaning you can assign them to variables of any type.
let nullable: string | null = null;
let notDefined: undefined = undefined;
5. Type Inference and Type Annotations
Type Inference
TypeScript can automatically infer the type of a variable based on the value assigned to it. This is known as type inference.
let inferredString = "Hello"; // TypeScript infers the type as string
Type Annotations
You can explicitly declare the type of a variable using type annotations. This is useful for clarity and ensuring the variable is used correctly.
let annotatedString: string = "Hello";
Example Code
Here’s a simple TypeScript example that utilizes these basic types:
enum Role {
Admin,
User,
Guest
}
function printUserInfo(name: string, age: number, isMember: boolean, role: Role): void {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Membership: ${isMember ? "Active" : "Inactive"}`);
console.log(`Role: ${Role[role]}`);
}
let userName: string = "Alice";
let userAge: number = 28;
let userIsMember: boolean = true;
let userRole: Role = Role.User;
printUserInfo(userName, userAge, userIsMember, userRole);
Summary
Today, we covered the basic types in TypeScript, including primitive types, arrays, tuples, enums, and special types like any
, unknown
, void
, null
, and undefined
. We also discussed type inference and type annotations. Understanding these basics will help you write more robust and type-safe code.
Next time, we'll explore functions in TypeScript. Stay tuned!