This chapter explores the various data types available in TypeScript, including their syntax, usage, and practical applications. For instance, understanding the difference between null and undefined can help avoid errors when dealing with uninitialized variables, ensuring cleaner and more predictable code. By understanding TypeScript’s type system, developers can write robust and error-free code with improved readability and maintainability.
Chapter Goal
- To familiarize readers with TypeScript’s core data types.
- To understand how to use and combine data types effectively.
- To learn best practices for leveraging TypeScript’s type system.
Key Characteristics for TypeScript Data Types
- Static typing: TypeScript ensures variables have a predefined type that cannot be changed.
- Type inference: Automatically determines the type of a variable if not explicitly defined.
- Advanced types: Allows complex type definitions such as unions, intersections, and generics.
- Compatibility: Built on JavaScript’s dynamic type system while adding type safety.
Basic Rules for TypeScript Data Types
- Always use explicit type annotations where clarity is needed.
- Utilize any type sparingly as it disables type checking. For example, any can be useful when dealing with third-party libraries or dynamic data:
let dynamicData: any = fetchData(); // Allows flexibility for unknown data.
However, overusing any can lead to issues:
let data: any = ‘hello’;
data.toUpperCase(); // Works
data = 42;
data.toUpperCase(); // Runtime error
It is better to use unknown or strict types whenever possible to ensure type safety. 3. Combine types using union (|) and intersection (&) types for flexibility. 4. Prefer unknown over any for safer type handling. 5. Use type aliases or interfaces for complex structures.
Best Practices
- Favor strict typing for better predictability and fewer runtime errors.
- Avoid mixing different types unless necessary and intentional.
- Use enum for fixed sets of related constants.
- Regularly validate types when working with external data.
- Use IDEs with TypeScript support for real-time type checking.
Syntax Table
Serial No | Data Type | Syntax Example | Description |
1 | Number | let age: number = 25; | Represents numeric values. |
2 | String | let name: string = ‘John’; | Represents text values. |
3 | Boolean | let isValid: boolean = true; | Represents true/false values. |
4 | Array | let list: number[] = [1, 2]; | Represents a collection of values. |
5 | Tuple | let tuple: [string, number]; | Represents an array with fixed types/order. |
6 | Enum | enum Color { Red, Green }; | Represents a group of named constants. |
7 | Any | let data: any = 42; | Allows assignment of any type. |
8 | Void | function log(): void {} | Represents functions with no return value. |
9 | Null and Undefined | let value: null = null; | Represents absence of value. |
Syntax Explanation
Number
What is Number Type
Represents numeric values, including integers and floating-point numbers. TypeScript also supports numeric literals such as binary (e.g., 0b1010) and hexadecimal (e.g., 0x1A).
Syntax
let age: number = 25;
Detailed Explanation
- Supports arithmetic operations.
- Can represent NaN and Infinity.
Example
let price: number = 99.99;
let discount: number = price * 0.1;
Output
Discount: 9.999
Notes
- Avoid mixing numeric and string types in calculations.
Warnings
- Be cautious with NaN in arithmetic operations.
String
What is String Type
Represents text values enclosed in single, double, or backticks.
Syntax
let name: string = ‘John’;
Detailed Explanation
- Supports template literals for embedding expressions.
Example
let greeting: string = `Hello, ${name}!`;
Output
Hello, John!
Notes
- Use template literals for cleaner concatenation.
Warnings
- Avoid mismatched quotes in string declarations.
Boolean
What is Boolean Type
Represents true/false values.
Syntax
let isValid: boolean = true;
Detailed Explanation
- Often used in conditional statements.
Example
if (isValid) {
console.log(‘Valid!’);
}
Output
Valid!
Notes
- Use booleans for clear intent in logic.
Warnings
- Avoid using non-boolean values in boolean contexts.
Array
What is Array Type
Represents a collection of values of the same type.
Syntax
let list: number[] = [1, 2, 3];
Detailed Explanation
- Can be initialized empty or with predefined values.
- Supports common array operations like push, pop, and iteration.
Example
let numbers: number[] = [1, 2, 3];
numbers.push(4);
console.log(numbers);
Output
[1, 2, 3, 4]
Notes
- Use type annotations to prevent unintended value types.
Warnings
- Avoid mixing types unless explicitly allowed.
Tuple
What is Tuple Type
An array with fixed types and order for its elements.
Syntax
let tuple: [string, number];
Detailed Explanation
- Each element in the tuple must match the specified type.
Example
let user: [string, number] = [‘Alice’, 25];
Output
[‘Alice’, 25]
Notes
- Useful for representing fixed structures like coordinates.
Warnings
- Modifying tuple elements must respect the defined types.
Enum
What is Enum Type
A set of named constants representing related values.
Syntax
enum Color { Red, Green, Blue };
Detailed Explanation
- Each enum member gets an auto-incremented value starting from 0.
Example
enum Color { Red, Green, Blue };
let backgroundColor: Color = Color.Green;
Output
1
Notes
- Use enums to represent a set of related constants.
Warnings
- Avoid assigning conflicting values to enum members.
Any
What is Any Type
Allows variables to accept values of any type.
Syntax
let data: any = 42;
Detailed Explanation
- Disables strict type checking, useful for dynamic or unknown types.
Example
let value: any = ‘Hello’;
value = 123;
Output
No specific output.
Notes
- Use sparingly as it undermines type safety.
Warnings
- Overuse can lead to runtime errors.
Void
What is Void Type
Represents the absence of any value.
Syntax
function logMessage(): void {
console.log(‘This is a log message.’);
}
Detailed Explanation
- Commonly used for functions that do not return a value.
Example
logMessage();
Output
This is a log message.
Notes
- Void functions should have no return statements, but they can still execute side effects such as logging messages or modifying external states.
Warnings
- Avoid using void for variable types.
Null and Undefined
What are Null and Undefined Types
Represent the absence of a value or an uninitialized state.
Syntax
let value: null = null;
let notDefined: undefined = undefined;
Detailed Explanation
- null indicates the intentional absence of a value.
- undefined represents variables that have not been assigned a value.
Example
let nullableValue: string | null = null;
nullableValue = ‘Hello’;
Output
Hello
Notes
- Use union types to allow nullability.
Warnings
- Avoid null unless explicitly required by design.
Real-Life Project
Project Name
Data Processing with TypeScript Types
Project Goal
Demonstrates how to use various TypeScript data types in a data processing context, ensuring type safety and clarity.
Code for This Project
interface Product {
id: number;
name: string;
price: number;
tags: string[];
discount?: number;
}
const products: Product[] = [
{ id: 1, name: 'Laptop', price: 1500, tags: ['electronics', 'computers'] },
{ id: 2, name: 'Phone', price: 800, tags: ['electronics'], discount: 10 },
{ id: 3, name: 'Book', price: 20, tags: ['education', 'literature'] },
];
function calculateFinalPrice(product: Product): number {
const discount = product.discount ?? 0;
return product.price - (product.price * discount) / 100;
}
products.forEach(product => {
console.log(
`${product.name} costs $${calculateFinalPrice(product).toFixed(2)}`
);
});
Save and Run
- Save the code to a file, e.g., dataProcessing.ts.
- Compile the TypeScript code using tsc dataProcessing.ts.
- Run the resulting JavaScript file using node dataProcessing.js.
Expected Output
Laptop costs $1500.00
Phone costs $720.00
Book costs $20.00
Insights
- Optional properties like discount are handled gracefully with default values.
- Arrays with structured objects enforce consistency in data handling.
- TypeScript enhances readability and reduces bugs in complex data workflows.
Key Takeaways
- TypeScript’s data types provide a robust framework for structured data.
- Leveraging optional properties and type inference minimizes error potential.
- Clear data processing logic benefits from TypeScript’s strong typing system.