TypeScript

3. Complete Guide to TypeScript Data Types: Built-in and User-defined Types Explained

๐Ÿ“š 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 null indicates 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.

Leave a Reply

Your email address will not be published. Required fields are marked *