In this tutorial, we'll learn how to use basic types in TypeScript.
TypeScript, a superset of JavaScript, introduces static typing to help developers write safer, more robust code. Understanding basic types and how to declare variable types is foundational to mastering TypeScript.
What Are Basic Types in TypeScript?
In TypeScript, types are the building blocks that enable type safety. They ensure that a variable holds the data you expect, helping to catch errors early in development. TypeScript provides a variety of basic types to model your data accurately.
Use Basic Types in TypeScript
Let’s explore the key basic types:
1. Number
The number type represents numeric values, including integers and floating-point numbers. It is equivalent to JavaScript’s Number.
let age: number = 25; // integer
let temperature: number = 36.6; // floating-point
let hex: number = 0xff; // hexadecimal
let binary: number = 0b1010; // binary
let octal: number = 0o744; // octal
2. String
The string type is used for textual data. Strings in TypeScript can be enclosed in single quotes, double quotes, or template literals (backticks).
let firstName: string = "John";
let lastName: string = 'Doe';
let fullName: string = `${firstName} ${lastName}`; // Template literal
3. Boolean
The boolean type can only have two values: true or false.
let isActive: boolean = true;
let isVerified: boolean = false;
4. Array
The array type can hold a collection of values of the same type. You can declare an array using two syntaxes:
Using square brackets []
:
let numbers: number[] = [1, 2, 3, 4, 5];
Using Array<type>
:
let fruits: Array<string> = ["apple", "banana", "cherry"];
5. Tuple
A tuple is a fixed-length array where each element can have a different type.
let user: [string, number] = ["Alice", 30];
6. Enum
An enum is a way to define a set of named constants. By default, enum
values are numeric and incremented automatically.
enum Color {
Red, // 0
Green, // 1
Blue, // 2
}
let favoriteColor: Color = Color.Green;
console.log(favoriteColor); // Output: 1
// You can also specify custom values
enum Status {
Active = 1,
Inactive = 0,
Pending = -1,
}
let currentStatus: Status = Status.Pending;
console.log(currentStatus); // Output: -1
7. Any
The any type can hold any value. It’s useful when migrating JavaScript code or dealing with dynamic content but should be used sparingly to avoid losing type safety.
let data: any = 5;
data = "Hello"; // Allowed
data = true; // Also allowed
8. Void
The void type is used to represent the absence of a value, typically for functions that do not return anything.
function logMessage(message: string): void {
console.log(message);
}
9. Null and Undefined
null and undefined are their own types in TypeScript. They are subtypes of all other types unless you use the strictNullChecks option.
let u: undefined = undefined;
let n: null = null;
10. Never
The never type represents values that never occur. It’s used for functions that always throw an error or have infinite loops.
function throwError(message: string): never {
throw new Error(message);
}
Declaring Variable Types in TypeScript
Declaring variable types explicitly in TypeScript ensures that variables only hold data of a specified type. This is done by appending a colon (:) followed by the type after the variable name.
1. Explicit Type Declaration
You declare the type of a variable explicitly when you know its intended type.
let username: string = "tech_user";
let score: number = 99.9;
let isCompleted: boolean = true;
2. Type Inference
TypeScript can infer the type of a variable based on its assigned value. While explicit declarations are encouraged for clarity, inference helps simplify the code.
let city = "London"; // Inferred as string
let count = 42; // Inferred as number
3. Union Types
A variable can hold more than one type using union types, defined with a pipe (|).
let identifier: string | number;
identifier = "ABC123"; // Valid
identifier = 456; // Also valid
4. Literal Types
Literal types allow a variable to have a specific, exact value.
let direction: "north" | "south" | "east" | "west";
direction = "north"; // Valid
// direction = "up"; // Error: Type '"up"' is not assignable
5. Type Aliases
To make your code more readable and reusable, you can define custom types using type aliases.
type ID = string | number;
let userID: ID = 101;
let orderID: ID = "ORD123";
6. Function Parameter and Return Types
You can declare types for function parameters and return values.
function add(a: number, b: number): number {
return a + b;
}
function greet(name: string): string {
return `Hello, ${name}`;
}
7. Optional and Default Parameters
You can make function parameters optional using the ? operator or provide default values.
function log(value: string, prefix?: string): void {
console.log(`${prefix || ""}${value}`);
}
log("TypeScript"); // Output: TypeScript
log("TypeScript", "Welcome to "); // Output: Welcome to TypeScript
Conclusion
In this tutorial, we've learnt how to use basic types in TypeScript. Understanding basic types and how to declare variable types in TypeScript is essential for writing safe and maintainable code. The robust type system prevents many runtime errors by catching them at compile time. With practice, you'll find that using TypeScript improves your productivity and confidence in your code.