Number Data Type in TypeScript
The number
data type in TypeScript is used to represent both integer and floating-point numbers. It is analogous to the number
type in JavaScript and does not differentiate between different types of numeric values.
Basic Usage
The number
type can be used to store any kind of numeric value, including integers and floating-point numbers. Here’s a basic example:
let age: number = 25;
let temperature: number = 36.6;
console.log(age, temperature); // Output: 25 36.6
Numeric Operations
TypeScript supports various numeric operations such as addition, subtraction, multiplication, and division. Here’s how you can perform some common numeric operations:
let a: number = 10;
let b: number = 5;
let sum: number = a + b; // Addition
let difference: number = a - b; // Subtraction
let product: number = a * b; // Multiplication
let quotient: number = a / b; // Division
console.log(sum, difference, product, quotient); // Output: 15 5 50 2
Special Numeric Values
TypeScript, like JavaScript, also supports special numeric values such as NaN
(Not-a-Number), Infinity
, and -Infinity
:
let notANumber: number = NaN;
let positiveInfinity: number = Infinity;
let negativeInfinity: number = -Infinity;
console.log(notANumber, positiveInfinity, negativeInfinity); // Output: NaN Infinity -Infinity
Type Annotations and Type Inference
TypeScript provides type annotations to explicitly define the type of a variable. It also uses type inference to automatically determine the type based on the assigned value:
let explicitNumber: number = 42; // Explicit type annotation
let inferredNumber = 42; // TypeScript infers the type as number
Conclusion
The number
type in TypeScript is versatile and supports various numeric operations and special values. Understanding how to use the number
type effectively allows you to perform calculations and manage numeric data efficiently in your TypeScript projects.
Comments
Post a Comment