TypeScript Data Types
Data Types in TypeScript
Data types define the kind of data a variable can hold, ensuring better organization, fewer errors, and improved code readability. In TypeScript, strong typing is used to catch errors early, making your code more reliable and maintainable.
TypeScript supports a wide range of data types, from simple types likeboolean
,number
, andstring
to more complex ones likearrays
,tuples
, andenums
. By understanding and using these data types effectively, developers can write robust and predictable code.
1. Boolean
A boolean
represents either true
or false
. It is used to control logic, such as deciding whether a condition is met or not.
Use Case:
Tracking on/off states like a toggle switch or user login status.
tsx
1let isActive: boolean = true;
2let hasCompleted: boolean = false;
2. Number
The number
type represents all numeric values, including integers and floating-point numbers. It is used for calculations, counters, and numeric operations.
Use Case:
Storing quantities, ages, or mathematical results.
tsx
1let age: number = 25;
2let pi: number = 3.14;
3. String
A string
stores textual data, like names or messages. It supports template literals for dynamic content.
Use Case:
Storing user names, messages, or content that needs to be displayed.
tsx
1let welcomeMessage: string = `Welcome, John!`;
4. Array
Arrays are used to store multiple values of the same type in an ordered collection.
Use Case:
Storing lists like product names, user IDs, or numerical data.
tsx
1let scores: number[] = [85, 90, 78];
5. Tuple
Tuples store a fixed number of elements with specified types, such as a combination of related values.
Use Case:
Storing grouped data, like a user’s name and age together.
tsx
1let userInfo: [string, number] = ["Alice", 25];
6. Enum
An enum
defines a set of named constants, making code more readable and meaningful.
Use Case:
Representing predefined options like user roles or statuses.
tsx
1enum Role { Admin, User, Guest }
2let userRole: Role = Role.Admin;
7. Unknown
The unknown
type is safer than any
and requires type checking before use. It is useful for values with uncertain types.
Use Case:
Handling external input like user-provided data or API responses.
tsx
1let data: unknown = "Hello";
2if (typeof data === "string") {
3 console.log(data.toUpperCase());
4}
8. Any
The any
type can hold any value and bypasses TypeScript’s type checking. It should be used sparingly.
Use Case:
Dealing with legacy code or highly dynamic data.
tsx
1let randomValue: any = 42;
2randomValue = "A string now!";
9. Void
The void
type indicates a function doesn’t return a value. It’s used for functions that perform actions rather than calculations.
Use Case:
Logging messages or triggering events.
tsx
1function logMessage(msg: string): void {
2 console.log(msg);
3}
10. Null and Undefined
These types represent the absence of a value. null
is used for explicitly empty values, while undefined
means a variable hasn’t been initialized.
Use Case:
Handling optional fields or empty data.
tsx
1let result: null = null;
2let value: undefined = undefined;
11. Never
The never
type is used for functions that never return, such as those that throw errors or run infinitely.
Use Case:
Error handling or indicating unreachable code.
tsx
1function throwError(msg: string): never {
2 throw new Error(msg);
3}
12. Object
The object
type represents non-primitive values like arrays, functions, or plain objects.
Use Case:
Storing structured data like user profiles or settings.
tsx
1let user: object = { name: "John", age: 30 };
13. Type Assertions
Type assertions allow you to manually specify a type when TypeScript cannot infer it accurately.
Use Case:
When the developer knows more about a variable’s type than TypeScript.
tsx
1let value: any = "Hello";
2let valueLength: number = (value as string).length;