Data Types in TypeScript
This article explains data types in TypeScript.
YouTube Video
Data Types in TypeScript
TypeScript offers a variety of data types. This allows you to define strict types for variables, function arguments, and return values. Below are the main data types and their usage.
Primitive Types
number Type
1let age: number = 25;
2console.log(age); // Outputs: 25
3console.log(typeof age); // Outputs: number
number
is a type used for handling numerical values, including integers and floating-point numbers (decimals). Handling values that exceed certain limits results inInfinity
orNaN
(Not-a-Number).
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
-
In TypeScript, numbers are represented as floating point numbers. This may result in slight inaccuracies in calculation results.
-
When precise calculations are required, such as financial amounts, it is necessary to avoid rounding errors like this. For example, you can use
BigInt
ortoFixed()
, or adjust the decimal places using libraries likedecimal.js
.
string Type
The string
type handles textual data.
1let greeting: string = "Hello, TypeScript!";
2console.log(greeting); // Outputs: Hello, TypeScript!
3console.log(typeof greeting); // Outputs: string
boolean (Logical Type)
The boolean
type has two values: true
or false
.
1let isOpen: boolean = true;
2console.log(isOpen); // Outputs: true
3console.log(typeof isOpen); // Outputs: boolean
null and undefined
null
represents a 'non-existent value', and undefined
represents an 'undefined value'.
1let emptyValue: null = null;
2let notDefined: undefined = undefined;
3
4console.log(emptyValue); // Outputs: null
5console.log(typeof emptyValue); // Outputs: object (JavaScript specification)
6
7console.log(notDefined); // Outputs: undefined
8console.log(typeof notDefined); // Outputs: undefined
Array
In TypeScript, you can specify the type of array elements. number[]
is an array of numbers, and string[]
is an array of strings.
1let numbers: number[] = [1, 2, 3, 4];
2console.log(numbers); // Outputs: [1, 2, 3, 4]
3console.log(typeof numbers); // Outputs: object
4
5let words: string[] = ["TypeScript", "JavaScript"];
6console.log(words); // Outputs: ["TypeScript", "JavaScript"]
7console.log(typeof words); // Outputs: object
Tuple
A tuple is an array with elements of different types.
1let person: [string, number] = ["Alice", 30];
2console.log(person); // Outputs: ["Alice", 30]
3console.log(typeof person); // Outputs: object
Enum
enum
defines a set of named constants.
1enum Color {
2 Red,
3 Green,
4 Blue
5}
6
7let favoriteColor: Color = Color.Green;
8console.log(favoriteColor); // Outputs: 1 (Defaults start from 0)
9console.log(typeof favoriteColor); // Outputs: number
any
The any
type can hold any type of value and is used when you want to disable type checking.
1let anything: any = "Hello";
2console.log(anything); // Outputs: Hello
3console.log(typeof anything); // Outputs: string
4
5anything = 42;
6console.log(anything); // Outputs: 42
7console.log(typeof anything); // Outputs: number
Union Type
Using Union types, you can define variables that can hold one of multiple types.
1let identifier: number | string = "ID_12345";
2console.log(identifier); // Outputs: ID_12345
3console.log(typeof identifier); // Outputs: string
4
5identifier = 12345;
6console.log(identifier); // Outputs: 12345
7console.log(typeof identifier); // Outputs: number
Summary
number
,string
,boolean
: Primitive types.null
,undefined
: Special values.Array
: An array with type annotations.Tuple
: An array with elements of different types.enum
: An enumerated type.any
: Any type.Union
: A variable that can take one of multiple types.
By using these data types, TypeScript enhances type safety, making it easier to prevent errors during development.
Wrapper Objects
Wrapper Objects in TypeScript are objects automatically created to treat primitive data types as objects. Primitive types allow for lightweight and fast operations, while object types have methods and properties, enabling richer operations.
In JavaScript (and TypeScript), there are wrapper objects corresponding to primitive types like string
, number
, and boolean
. They are created using constructor functions called String
, Number
, and Boolean
, respectively.
Below are examples of wrapper objects.
String Object
The String
object provides properties and methods for strings.
1let strPrimitive: string = "Hello, World!";
2let strObject: String = new String("Hello, World!");
3
4console.log(strPrimitive); // Outputs: Hello, World!
5console.log(typeof strPrimitive); // Outputs: string
6
7console.log(strObject); // Outputs: [String: 'Hello, World!']
8console.log(typeof strObject); // Outputs: object
Features:
- Unlike primitive
string
, aString
object is treated asobject
bytypeof
. - Wrapper objects are useful when manipulating strings or calling methods on them.
Number Object
The Number
object provides properties and methods for numbers.
1let numPrimitive: number = 42;
2let numObject: Number = new Number(42);
3
4console.log(numPrimitive); // Outputs: 42
5console.log(typeof numPrimitive); // Outputs: number
6
7console.log(numObject); // Outputs: [Number: 42]
8console.log(typeof numObject); // Outputs: object
Features:
- The
Number
object, as a wrapper for numbers, includes methods for numerical operations (e.g.,toFixed
).
Boolean Object
The Boolean
object provides properties and methods for boolean values.
1let boolPrimitive: boolean = true;
2let boolObject: Boolean = new Boolean(true);
3
4console.log(boolPrimitive); // Outputs: true
5console.log(typeof boolPrimitive); // Outputs: boolean
6
7console.log(boolObject); // Outputs: [Boolean: true]
8console.log(typeof boolObject); // Outputs: object
Features:
- The
Boolean
object is a wrapper for the primitiveboolean
type and is treated asobject
.
Differences between Wrapper Objects and Primitive Types
Since wrapper objects are treated as objects, there is a slight performance decrease, but more functional operations are possible due to added properties and methods. Moreover, there are differences in comparison using ==
and ===
.
1let numPrimitive: number = 123;
2let numObject: Number = new Number(123);
3
4console.log('== : ', numPrimitive == numObject); // Outputs: true (Value comparison)
5console.log('=== : ', numPrimitive === numObject); // Outputs: false (Due to differing types)
Features:
==
compares values, while===
strictly compares including types.===
returnsfalse
when comparing wrapper objects with primitive types.
Type Conversion
In TypeScript, it is important to properly manage implicit and explicit type conversions.
Implicit Type Conversion
- In TypeScript, implicit type conversions should be avoided as much as possible to ensure type safety.
1const result: string = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
- In this example, the number
5
is implicitly converted to a string, resulting in the string"55"
.
Explicit Type Conversion
- In TypeScript, use type annotations or type conversion functions to safely perform type conversions.
1const num: string = "123";
2const convertedNum: number = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
- In this example, the
Number()
function is used to explicitly convert the string"123"
into the number123
.
Type Checking
In TypeScript, you can use the typeof
operator to check the data type of a variable.
1// Output: The type of 42 is: number
2console.log('The type of 42 is:', typeof 42);
3
4// Output: The type of 42 is: bigint
5console.log('The type of 42n is:', typeof 42n);
6
7// Output: The type of "hello" is: string
8console.log('The type of "hello" is:', typeof "hello");
9
10// Output: The type of true is: boolean
11console.log('The type of true is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol() is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {} is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
- In TypeScript, you can use
typeof
to check types, but for more precise type checking, it is also recommended to use theinstanceof
oris
operators.
Summary
- Wrapper Objects are treated as objects because they provide additional methods and properties for primitive types.
String
,Number
, andBoolean
are representative examples of wrapper objects.- Unlike primitive types, wrapper objects are identified as
object
bytypeof
.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.