๐ TypeScript Data Types
As discussed earlier, JavaScript is a loosely typed language because it does not require explicitly defining data types for variables.
However, that doesn’t mean JavaScript lacks data types โ it definitely has them!
The key difference between JavaScript and TypeScript is:
- In JavaScript, types are handled internally (automatic typecasting).
- In TypeScript, you can explicitly define a data type โ and TypeScript enforces it (though defining types is optional).
TypeScript offers a powerful and flexible type system. Here’s how it classifies data types:
๐ฏ The Any Type
- The
any type is the super type of all types in TypeScript. - When you use
any, you tell the compiler not to perform any type checking on that variable. - It gives flexibility but removes type safety.
Example:
let data: any = 5;
data = "Hello World";
data = true;
๐ Built-in Types
TypeScript provides several built-in data types:
| ๐ Data Type | ๐ท Keyword | ๐ Description |
|---|---|---|
| Number | number |
Double precision 64-bit floating point values. Used for both integers and fractions. |
| String | string |
Represents a sequence of Unicode characters. |
| Boolean | boolean |
Represents logical values: true or false. |
| Void | void |
Used for functions that do not return any value. |
| Null | null |
Represents the intentional absence of any object value. |
| Undefined | undefined |
Represents uninitialized variables. |
โก Note: There is no separate “integer” type in TypeScript or JavaScript โ everything numeric is of type
number.
๐ค Null and Undefined โ Are They the Same?
Short answer: โ No, they are not the same!
- Undefined: A variable that has been declared but not assigned any value automatically gets
undefined. - Null: A variable explicitly assigned
nullindicates a deliberate non-value or “empty” object reference.
Both represent “absence” of value, but they serve different purposes in programming.
๐ User-defined Data Types
TypeScript not only supports built-in types but also provides user-defined types to build complex applications:
- ๐งฉ Enumerations (enums)
- ๐ Classes
- ๐งพ Interfaces
- ๐ฆ Arrays
- ๐ฏ Tuples
These allow developers to structure their code in a clear, scalable, and object-oriented way.
