TypeScript Number Type
The number type in TypeScript represents all numeric values, including integers and floats. JavaScript's single number type is used here as well, allowing flexible numerical operations.
Declaring Variables with Number Type
let age: number = 30;
let price: number = 99.99;
Both an integer (30) and a floating-point number (99.99) are defined as numbers. Assigning non-numeric values causes errors.
Type Inference
let score = 100;
TypeScript automatically infers the 'score' variable as a number, ensuring type safety without explicit declarations.
Mathematical Operations
let x = 10;
let y = 5;
let total = x + y;
Basic arithmetic operations like addition, subtraction, multiplication, and division can be safely performed with the number type.
Using Number in Functions
function double(value: number): number {
return value * 2;
}
Function definitions using number types ensure parameters and return values are numeric, preventing invalid inputs.
Why Is Number Type Important?
Handling numerical data is essential in software. TypeScript’s number type maintains data integrity in calculations, scoring, and user input.
Back